我已经知道React Native单向的所有理论和类似的东西,我想要的是一段代码,显示如何更新另一个组件的状态。
我尝试了这个样本:
class Parent extends React.Component {
constructor(props) {
super(props)
// Bind the this context to the handler function
this.handler = this.handler.bind(this);
// Set some state
this.state = {
messageShown: false
};
}
// This method will be sent to the child component
handler() {
this.setState({
messageShown: true
});
}
// Render the child component and set the action property with the handler as value
render() {
return <Child action={this.handler} />
}
}
class Child extends React.Component {
render() {
return (
<div>
{/* The button will execute the handler function set by the parent component */}
<Button onClick={this.props.action} />
</div>
)
}
}
它似乎对我不起作用。按下按钮似乎什么也没发生或做任何事情!
此外,如果我在Parent render()中添加子组件,那么子UI将显示在我的父级上,我不想...如何只更新Parent!