gpt4 book ai didi

javascript - 父组件如何在 React 中改变子组件的 props?

转载 作者:行者123 更新时间:2023-12-03 05:34:53 25 4
gpt4 key购买 nike

我是个新手,对某些事情有点困惑。我在网上读过很多文章,声称组件无法更改其自己的 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 的 Material 都说父级可以更改其子级的 props。我可以正常工作的内容如下:

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} />
);
}
}

当我唯一想要重新渲染的是 subview 时,父级需要重新渲染对我来说似乎有点过分了。如何更改<Child>的 Prop 来自 <Parent> 的组件成分?

次要问题

1)是否可以在不重新渲染组件的情况下更改组件的状态?

2) 有没有onStateChange输入我们可以利用的事件,或者我们只有 componentWillReceiveProps

最佳答案

1) Is it possible to change the state of a component without having the component re-render?

不,这没有什么意义。

2) Is there an onStateChange type event that we can tap into, or do we solely have componentWillReceiveProps?

没有,使用componentWillReceiveProps

It seems a bit overkill to me that the Parent needs to re-render when the only thing that I want to re-render is the child view.

实际上,这就是你欺骗自己的地方:父级已更改,因为它返回的内容已更改。整棵树从根开始重新渲染。

关于javascript - 父组件如何在 React 中改变子组件的 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40777002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com