Home >Web Front-end >Front-end Q&A >How to modify value in react
How to modify the value in react: 1. Open the corresponding front-end code file and get the parameters on the label; 2. Add a bind pointer to the place where the method is called; 3. Use bind to change the direction of this; 4. Use Just modify the value in the state state.
#The operating environment of this tutorial: Windows 10 system, react18 version, Dell G3 computer.
How to modify the value in react?
react component clicks to modify the value state
Changes the value on the label when clicked, but this cannot be obtained in the method, so the first thing to do is Just change this
class Leo extends React.Component{ render(){ return (<div> <input type="button" value="点击" onClick={this.show}/> <br/> //span获取标签上的参数 <span>{this.props.a}</span> <h1>sadfsdf</h1> </div>) } show(){ console.log(this)//在方法里如果直接调用this;打印出来会为Null,所以我们要做的就是改变this,需要在方法调用的地方加一个bind指向 } } ReactDOM.render(<Leo a='12'/>,app)
Use bind to change the direction of this
class Leo extends React.Component{ render(){ return (<div> <input type="button" value="点击" onClick={this.show.bind(this)}/> <br/> //span获取标签上的参数 <span>{this.props.a}</span> <h1>sadfsdf</h1> </div>) } show(){ console.log(this)//在方法里如果直接调用this;打印出来会为Null,所以我们要做的就是改变this,需要在方法调用的地方加一个bind指向 } } ReactDOM.render(<Leo a='12'/>,app)##Requirement: Modify the value in this.props.a
<script type="text/babel"> class Leo extends React.Component{ render(){ return (<div> <input type="button" value="点击" onClick={this.show.bind(this)}/> <br/> //span获取标签上的参数 <span>{this.props.a}</span> <h1>sadfsdf</h1> </div>) } show(){ this.props.a = 12 //如果直接这样修改发面会报错,read only(只能读不能修改);如果要修改就应该用state状态 } } ReactDOM.render(<Leo a='12'/>,app) </script>Use the state state to modify the value, you need to use the constructor to initializetip: props cannot change the value, but the state can be changed using setState
<script type="text/babel"> class Leo extends React.Component{ constructor(){ super(); this.state = { msg:'hello react ' } } render(){ return (<div> <input type="button" value="点击" onClick={this.show.bind(this)}/> <br/> //hello react <span>{this.state.msg}</span> <h1>sadfsdf</h1> </div>) } show(){ this.setState({//点击修改span里的值 msg:'哈哈' }) } } ReactDOM.render(<Leo/>,app) </script>Recommended learning: "
react video tutorial"
The above is the detailed content of How to modify value in react. For more information, please follow other related articles on the PHP Chinese website!