[英]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.