[英]Setting and resetting states in React.js
我正在嘗試在網頁中構建一個部分,其中在2X2網格中顯示四個組件。 當您單擊一個時,該框將擴展到屏幕的中心,而其他框則淡出。 我已經通過在幾個不同的屬性上調用setState來切換CSS類來弄清楚了這一部分。
我遇到的麻煩是,當按下“關閉”按鈕時會重置狀態,以使框呈現其原始形狀和不透明度。 我從“ handleCloseClick”功能中看到一個console.log,所以我知道它是有線屬性。 無論我如何遍歷狀態數組,都無法將其屬性更改回其原始狀態。 這是我的代碼。
class Parent extends Component{
constructor(){
super();
this.state =
attrs: {[{
id: 1,
expand: false,
reduced: false,
seeText: false
}],
[{
id: 2,
expand: false,
reduced: false,
seeText: false
}],
[{
id: 3,
expand: false,
reduced: false,
seeText: false
}],
[{
id: 4
expand: false,
reduced: false,
seeText: false
}]}
this.handleClick = this.handleClick.bind(this)
this.handleCloseClick = this.handleClick.bind(this)
}
/*This function works*/
handleClick(e){
const array = this.state.attrs
array.map(function(element){
if(element.id === i){
element.reduced = false;
element.expand = true;
element.seeText = true;
}else{
element.reduced = true;
}
})
this.seState({attrs: array})
}
/*This function will console.log but will not setState of attrs*/
handleCloseClick(){
const newArray = this.state.attrs
newArray.map(function(element(){
element.expand = false;
element.reduced = false;
element.seeText = false;
})
this.setState(attrs: newArray})
}
render(){
const newEls = this.state.attrs;
return(
{newEls.map(function(newEl, index)){
return <Child key={index} onClick={this.handleClick(el)} onCloseClick={this.handleCloseClick()} />
}
)
}
}
請幫忙! 為什么該死的國家不會變回原來的位置?!?!
有幾個問題.map
返回一個新數組,它不會更改現有狀態。 因此,您需要將其分配給變量以查看更改。
另外,您必須在.map
返回一個值,或使用“隱式”返回 ({
vs {
。
handleCloseClick(){ const newArray = this.state.attrs.map(element => ({ element.expand = false; element.reduced = false; element.seeText = false; })) this.setState(attrs: newArray}) }
您還可以將初始狀態移到其自己的方法中,然后在構造函數中使用以及何時要重置它...
constructor() { ... this.state = this.initialState(); } close() { this.setState(this.initialState()); } initialState() { return { attrs: [ [{ id: 1, expand: false, reduced: false, seeText: false }], [{ id: 2, expand: false, reduced: false, seeText: false }], [{ id: 3, expand: false, reduced: false, seeText: false }], [{ id: 4 expand: false, reduced: false, seeText: false }]} ]} }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.