【问题标题】:Incrementing react values增加反应值
【发布时间】:2019-07-07 04:12:49
【问题描述】:

我对 reactJS 很陌生。我正在尝试制作一个按钮并增加文本中的值。我正在尝试制作一个通过反应增加值并显示的按钮

import React from 'react'
import ReactDom from 'react-dom'

class App extends React.Component {

   constructor(props){
       super(props);
       this.state = {counter: 1}
   }


 increment (e) {
   e.preventDefault();
   this.setState({
   counter : this.state.counter + 1
   });
 }

   render() {
    return  <button onClick={this.increment}> "this is a button " + {this.state.counter} </button>
   }

}

ReactDOM.render(
  <App/>,
  document.getElementById('container')
);

【问题讨论】:

    标签: javascript reactjs react-component


    【解决方案1】:

    需要正确绑定increment函数

    class App extends React.Component {
       constructor(props){
           super(props);
           this.state = {counter: 1}
       }
    
    
     increment(e){
       e.preventDefault();
       this.setState({
       counter : this.state.counter + 1
       });
     }
    
       render() {
        return  <button onClick={(e)=>this.increment(e)}> this is a button {this.state.counter} </button>
       }
    
    }
    
    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>
    <div id='app'></div>

    【讨论】:

      【解决方案2】:

      尝试更改您的render

      return (
        <button onClick={this.increment}>this is a button {this.state.counter}</button>
      );
      

      【讨论】:

        猜你喜欢
        • 2021-12-04
        • 2019-09-19
        • 1970-01-01
        • 1970-01-01
        • 2020-11-14
        • 2021-07-23
        • 2020-01-29
        • 2017-12-30
        • 1970-01-01
        相关资源
        最近更新 更多