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