gpt4 book ai didi

javascript - 如何在react中传递状态?

转载 作者:行者123 更新时间:2023-12-02 23:01:40 25 4
gpt4 key购买 nike

我需要在点击提交时获取“+”或“-”结果,但完全不知道如何处理。这是我点击“提交”之前的代码和结果

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/

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