如何通过状态反应?

时间:2019-09-02 13:03:01

标签: javascript

我需要在单击“提交”时得到“ +”或“-”结果,但根本不知道如何处理它。单击“提交”之前,这是我的验证结果代码

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>

2 个答案:

答案 0 :(得分:1)

您应该在构造函数中绑定您的递增和递减函数,并仅将方法作为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"));

答案 1 :(得分:0)

这应该工作:

class App extends React.Component {
  constructor() {
    super();
    this.state = {counter: 0, tempCounter: 0};
    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
      this.submit = this.submit.bind(this);
  }

  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>
    );
  }
  submit(){
       const tempCount = this.state.tempCounter;
       this.setState({counter: tempCounter})
  }
  increment() {
    const tempCount = this.state.tempCounter;
    this.setState({
       tempCounter: tempCount + 1 
    });
  }

  decrement() {
    const tempCount = this.state.tempCounter;
    this.setState({
       tempCounter: tempCount - 1 
    });
  }
}
ReactDOM.render(<App />, document.getElementById("app"));