我对reactJS非常陌生。我试图制作一个按钮并增加文本中的值。我试图制作一个通过react增加值并显示
的按钮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')
);
答案 0 :(得分:0)
尝试更改您的render
:
return (
<button onClick={this.increment}>this is a button {this.state.counter}</button>
);
答案 1 :(得分:0)
您需要正确绑定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>