gpt4 book ai didi

javascript - 从用户输入更改 setState

转载 作者:行者123 更新时间:2023-12-03 02:25:46 26 4
gpt4 key购买 nike

我对 React 还很陌生,正在尝试使用 React。我正在制作一组立方体,当用户单击时,它们会在颜色之间交替。

为了了解有关 setState 的更多信息,我添加了一个输入,以便当用户输入颜色时,立方体的颜色会发生变化。问题是立方体的颜色发生了变化,但是当我单击立方体时,它会返回到默认颜色。我希望立方体更改用户输入的颜色。

我尝试了什么?我尝试将 this.setState({color: 'pink'}) 中的粉红色更改为 setColor(),但它不起作用。我环顾四周,但找不到任何可以回答我的问题的东西。

我创建了问题 here .

class TicTacToe extends Component {

state = {
color: 'black',
colors: 'white',
count: 0
}

changeColor(c){
this.setState({ count: this.state.count + 1 })
if(this.state.count % 2 === 0){
this.setState({color: 'pink'})
this.setState({colors: 'grey'})
} else if (this.state.count % 2 !== 0){
this.setState({color: 'grey'})
this.setState({colors: 'pink'})
}
}

setColor(color){
return this.setState({color: color})
}

setColors(color){
this.setState({colors: color})
}

render(){
return (
<div className="main">
<div className="inputFields">
<span> Color One:
<input value={this.state.color}
onChange={(e)=> this.setColor(e.target.value)} /> </span>
<br /><br />

<span> Color Two:
<input value={this.state.colors}
onChange={(e)=> this.setColors(e.target.value)} /> </span>
</div>
<div onClick= {(c)=> this.changeColor()}>
<div className='square' style={{backgroundColor: this.state.color}}></div>
<div className='square' style={{backgroundColor: this.state.colors}}></div>
<div className='square' style={{backgroundColor: this.state.color}}></div>
<br />
<div className='square' style={{backgroundColor: this.state.colors}}></div>
<div className='square' style={{backgroundColor: this.state.color}}></div>
<div className='square' style={{backgroundColor: this.state.colors}}></div>
<br />
<div className='square' style={{backgroundColor: this.state.color}}></div>
<div className='square' style={{backgroundColor: this.state.colors}}></div>
<div className='square' style={{backgroundColor: this.state.color}}></div>
</div>
<span> This is the count: {this.state.count} </span>
</div>
)
}
}

export default TicTacToe;

最佳答案

它会返回到默认的onClick,因为onClick您正在手动设置颜色,而且您不需要计数变量在颜色之间交替。计数状态也没有正确使用。您所需要的只是使用函数 setState 并实现 changeColor ,例如

changeColor(c){
this.setState(prevState => ({
color: prevState.colors,
colors: prevState.color
}))
}

<强> Working Demo

检查When to use functional setState

检查setState doesn't update the state immediately

关于javascript - 从用户输入更改 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48959792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com