我是新来响应js的人,我想发生的事情是onClick中只有一个函数可以更改状态sampleCount的值。
这是我的代码:
constructor(props) {
super(props);
this.state = {
sampleCount: 5,
}
}
firstFunction = () = > {
this.setState({
sampleCount: 10
})
}
secondFunction = () = > {
this.setState({
sampleCount: 15
})
}
thirdFunction = () = > {
this.setState({
sampleCount: 20
})
}
内部返回
<div>
<button onClick={this.firstFunction}>Button 1 </button>
<button onClick={this.secondFunction}>Button 2 </button>
<button onClick={this.thirdFunction}>Button 3 </button>
<h1>{this.state.sampleCount}</h1>
</div>
是否只能使用一个可以根据值更改状态值的函数?如何?预先谢谢你
答案 0 :(得分:1)
您只需将函数包装在箭头函数中即可:
firstFunction = (value) => {
this.setState({ sampleCount: value})
}
<div>
<button onClick={() => this.firstFunction(5)}>Button 1 </button>
<button onClick={() => this.firstFunction(15)}>Button 2 </button>
<button onClick={() => this.firstFunction(20)}>Button 3 </button>
</div>
答案 1 :(得分:0)
您可以这样实现:
handleClick = (handleChangeValue) => {
this.setState({ sampleCount: handleChangeValue })
}
内部返回:
<div>
<button onClick={() => this.handleClick(5)}>Button 1 </button>
<button onClick={() => this.handleClick(15)}>Button 2 </button>
<button onClick={() => this.handleClick(20)}>Button 3 </button>
</div>
答案 2 :(得分:0)
简单的说明,请尝试这样。
constructor(props) {
super(props);
this.state = {
sampleCount: 5,
counts:[{buttonName:'button 1', count:10},
{buttonName:'button 2', count:15},
{buttonName:'button 3', count:20}]
}
}
changeCountFunction = (count) = > {
this.setState({
sampleCount: count
})
}
}
和内部收益
<div>
{this.state.counts.map((val)=>{
return <button key={val.count} onClick={()=>this.changeCountFunction(val.count)}>{val.buttonName}</button>
})}
</div>