[英]How to prevent one of the state variables of a child page from changing its value?How to retain initial value as props from the parent page? - ReactJS
当父级中名为“ isChildOpen”的标志为true时,将打开子页。 现在,我想使我的孩子中的状态变量filter2不可更改。 当我打开子页面时,filtered和filtered2应该从父项获得相同的值,但是尽管filterd可以在子项中的任何操作期间更改,但filterd2每次都应保留其打开子项的初始值。 当打开父级时,它应该从父级获取其值,但由于子级中的任何操作而不能更改。
子代码
class Child extends Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data,
filtered: this.props.filtered
filtered2: this.props.filtered
};
}
我尝试了Object.freeze,但没有帮助。
这是孩子从父页面打开的方式
{this.state.isChildOpen &&
<Child
data={this.state.data}
filtered={this.state.filtered}
/>}
有人可以在这方面帮助我吗? 在子级中的任何操作期间,filterd均可更改,但在刚刚打开子级后,filterd2应保留初始值。
我相信你可以使用this.props.filtered.slice()
这将复制该值
{this.state.isChildOpen &&
<Child
data={this.state.data}
filtered={this.state.filtered}
filtered2={this.state.filtered2}
/>}
当this.state.isChildOpen
开关为false,然后再真正的新实例Child
创建等构造再次与新值调用filtered2
。
您应该将isChildOpen
作为道具传递给Child
并从那里处理渲染
<Child
data={this.state.data}
filtered={this.state.filtered}
filtered2={this.state.filtered2}
isChildOpen={this.state.isChildOpen}
/>}
class Child extends Component {
constructor(props) {
super(props);
this.state = {
filtered2: this.props.filtered2
};
}
render() {
const { data, filtered, isChildOpen } = this.props; // this props will update following the parent
const { filtered2 } = this.state; //this prop will be controlled by the child and will keep the value once the instantiation
if(!isChildOpen) {
return null;
}
// otherwise render the component
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.