我需要在点击提交时获取“+”或“-”结果,但完全不知道如何处理。这是我点击“提交”之前的代码和结果
class App extends React.Component {
constructor() {
super();
this.state = {counter: 0};
}
render() {
return (
<div>
<button onClick={this.increment}>+</button>
<output>{this.state.counter}</output>
<button onClick={this.decrement}>-</button>
<button onClick={this.submit}>submit</button>
</div>
);
}
increment =()=> {
this.setState({
//counter: this.state.counter + 1
})
}
decrement=()=> {
this.setState({
//selectedFunction= -1??
})
}
submit=(selectedFunction)=>{this.setState({
counter: this.state.counter + {selectedFunction}
})};
}
ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
最佳答案
您应该在构造函数内绑定(bind)增量和减量函数,并仅将方法作为 onClick 属性传递。
class App extends React.Component {
constructor() {
super();
this.state = {counter: 0};
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
render() {
return (
<div>
<button onClick={this.increment}>+</button>
<output>{this.state.counter}</output>
<button onClick={this.decrement}>-</button>
</div>
);
}
increment() {
this.setState(function(prevState){
return { counter: prevState.counter + 1 }
});
}
decrement() {
this.setState(function(prevState){
return { counter: prevState.counter - 1 }
});
}
}
ReactDOM.render(<App />, document.getElementById("app"));
关于javascript - 如何在react中传递状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57757427/