【发布时间】:2017-08-07 09:24:37
【问题描述】:
假设我们有以下设置,父组件有两个子 C1 和 C2:
Example: container for C1 and C2, with a state called data
-C1: input, updates state in Example through handler passed as propdisplay, shows state from Example
-C2: display, shows state from Example
这里是代码和codepen:
class Example extends React.Component {
constructor (props) {
super(props)
this.state = { data: 'test' }
}
onUpdate (data) { this.setState({ data }) }
render () {
return (
<div>
<C1 onUpdate={this.onUpdate.bind(this)}/>
<C2 data={this.state.data}/>
</div>
)
}
}
class C1 extends React.Component {
constructor(props) {
super(props);
this.onUpdate = this.props.onUpdate;
}
render () {
return (
<div>
<input type='text' ref='myInput'/>
<input type='button' onClick={this.update.bind(this)} value='Update C2'/>
</div>
)
}
update () {
//this.props.onUpdate(this.refs.myInput.getDOMNode().value);
this.onUpdate(this.refs.myInput.getDOMNode().value);
}
}
class C2 extends React.Component {
constructor(props) {
super(props);
this.data = this.props.data;
}
render () {
return <div>{this.props.data}</div>
//return <div>{this.data}</div>
}
}
/*
* Render the above component into the div#app
*/
React.render(<Example />, document.getElementById('app'));
请注意,在 C2 的构造函数中,我们引用了 this.props.data。如果我们将该变量设置为像this.data = this.props.data 这样的类属性,即使我们单击更新按钮并且示例的 this.state.data 已更改,React 也无法更新 C1。我已经注释掉了直接引用 this.props.data 的行。
我的第一个想法是这一定是 React 中的非法语法。但是,用 C1 进一步测试表明,如果传入的 props 是函数而不是状态,则没有问题(请参阅 C1 的update 函数下的代码以确认我在说什么)。
为什么这对作为 props 传入的 state 不起作用,而对作为 props 传入的函数起作用?我假设 Example 看到 C1 已更改 data 状态,因此,调用 C2 的重新渲染,它使用 this.data 来确定接下来要渲染的内容。
【问题讨论】:
标签: javascript reactjs reactive-programming