我试图通过单击setState来使用从父元素传递来的属性来更新我的元素,但是我的元素的状态不会更新。
我尝试在一些地方添加和删除“ this”,并在构造函数中包含所有内容,但是无论出于何种原因,状态仍然不会改变。
changeToBlack = (e)=>{
this.setState({
buttonClicked:'black'})
}
render(){
return (
<div>
<button onClick={this.changeToRed}>change To Red</button>
<button onClick={this.changeToBlack}>change To Black</button>
<div className="grid">
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze} className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
</div>
</div>
);}
}
class Square extends Component{
constructor(props) {
super(props);
this.state = {
color: 'orange',
colorToChange:null,
changeColor: false
};
}
switchColor =(e)=>{
this.setState({
changeColor:true,
colorToChange:this.props.button})
}
render(){
return(
<input onMouseOver = {this.switchColor} style={{'height':'74px','width':'74px','backgroundColor':this.state.changeColor?this.state.color:this.state.colorToChange,'margin':'0'}}>
</input>
)
}
我真的不确定为什么colorToChange保持为null而changeColor保持为false。任何帮助将不胜感激。
答案 0 :(得分:1)
我认为您希望将这些变量四舍五入,因为它会将背景颜色设置为null
,然后将鼠标悬停在输入上后,它将始终将其设置为this.state.color
,该颜色始终为橙色
您应该更改:
this.state.changeColor?this.state.color:this.state.colorToChange
收件人:
this.state.changeColor ? this.state.colorToChange : this.state.color