【发布时间】:2017-02-17 21:09:17
【问题描述】:
假设我们有两个组件(父母和孩子),基本上我将父母状态变量发送到孩子的输入元素以进行一些操作。比如……
var Parent = React.createClass({
getInitialState: function() {
return {
name: ''
}
},
handleTextChange: function(e) {
this.setState({
name: e.target.value
})
},
render: function() {
return(
<div>
<input type="text" placeholder="Enter something" onChange={this.handleTextChange} />
<Child name={this.state.name} />
</div>
)
}
});
我的子组件看起来像这样..
var Child = React.createClass({
getInitialState: function() {
return {
childName: ''
}
},
componentWillReceiveProps: function(nextProps) {
this.setState({
childName: nextProps.name
})
},
handleChildTextChange: function(e) {
this.setState({
childName: e.target.value
})
},
render: function() {
return(
<div>
<input type="text" onChange={this.handleChildTextChange} placeholder={this.props.name} />
<h4>{this.state.childName}</h4>
</div>
)
}
});
基本上我想做三件事
- My Child 组件的 childName 值最初应设置为
父母的道具(this.props.name,这是父母的状态变量
name) - 更改我的
Child的输入后,目标文本应覆盖我的 家长姓名(this.props.name) - 如果我的孩子输入为空并且我的
Parent的名称正在更改,我 希望我的Child的组件状态变量childName是 来自父级的不断变化的道具(this.props.name)
有人可以帮我解决这个问题吗?
P.S : 我的 Child 的组件目标文本不应该更新我的 Parent 的状态变量(名称)我的意思是,没有回调作为道具。
【问题讨论】:
-
当您将它作为道具传递时,为什么要强制它处于内部状态?只需将其作为道具传递,并在值更改时传递处理程序
-
我将其添加到状态变量中,因为在更改我的子输入时,我希望将更改后的值分配给状态变量。此外,我只需要在子组件的初始渲染中使用 this.props.name。
-
这三点有帮助,为什么不设置一个额外的状态值来表明孩子“拥有”当前姓名,而不是父母?我稍微更新了答案
标签: javascript reactjs