【发布时间】:2017-04-08 04:51:58
【问题描述】:
我是新手,对某些事情有点困惑。我在网上读过很多文章,声称组件不能更改自己的 props,但父级可以更改其子级的 props。但是,我没有看到任何实际显示如何执行此操作的内容。
我希望能够做到这一点:
class Parent extends Component {
constructor(props) {
super(props);
this.childProps = {name:'name',age:12,type:'child'};
this.changeChild = this.changeChild.bind(this);
}
changeChildName(newName) {
//change prop 'name' of child here;
}
render() {
return (
<Child {...this.childProps} />
);
}
}
但是,我根本不知道该怎么做——尽管我在 React 上读到的几乎所有材料都说父母可以更改其孩子的道具。我可以正常工作的如下:
class Parent extends Component {
constructor(props) {
super(props);
this.state = {name:'name',age:12,type:'child'};
this.changeChild = this.changeChild.bind(this);
}
changeChildName(newName) {
this.setState({name: newName});
}
render() {
return (
<Child {...this.state} />
);
}
}
当我唯一想要重新渲染的是子视图时,父级需要重新渲染对我来说似乎有点矫枉过正。如何从<Parent> 组件更改<Child> 组件的道具?
次要问题
1) 是否可以在不重新渲染组件的情况下更改组件的状态?
2) 是否有我们可以利用的onStateChange 类型的事件,或者我们只有componentWillReceiveProps?
【问题讨论】:
-
对于那些不赞成这个问题的人,你能至少解释一下你为什么这样做吗?网上很多文章都说这应该是可能的。
标签: javascript reactjs ecmascript-6