父组件
import React, {Component} from 'react';
import NameContainer from '../nameContainer/index'
export default class Vishal extends Component {
constructor(props) {
super(props);
this.state = {
data: "This is the data"
}
}
render() {
return(
<div>
<p>My name is Vishal</p>
</div>
)
}
}
子组件
import React, {Component} from 'react';
export default class NameContainer extends Component {
}
如何使用回调函数和import from the child component
?任何帮助将不胜感激
这违反了自上而下的反应哲学和任何可能不是您想要走的劫持方式。
我认为您的意思是在父容器中具有状态,并允许孩子显示和更新该状态。
即Parent.JS
import React, {Component} from 'react';
export default class NameContainer extends Component {
this.state = { name: 'Vishal' }
handleChange = this.setState({name: event.target.value})
render() {
return (
<Vishal name={this.state.name} handleChange={this.handleChange} /> )}
然后在子js中// // Vishal.js
{ ...boilerplate }
handleChange = this.props.handleChange; // and e.g a button or textfield to allow the user to update the name.
render() {
return ( {this.props.name}) }}
这将在子组件Vishal.js中显示来自Parent.js的名称的有状态数据(初始化为'Vishal')
从React中的子组件更新父组件状态https://medium.com/@kyledavelaar/updating-parent-component-state-from-children-components-in-react-2ead9b9cec9f