增加反应值

Incrementing react values

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

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')
);

尝试更改您的 render:

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

您需要正确绑定 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>