简体   繁体   English

如何设置按钮点击反应js的值?

[英]how to set value on button click in react js?

I want to change the state value on button click using react js.I am able to get click event .But the set value not updated why .I used this 我想使用react js更改按钮单击时的状态值。我能够获得click事件。但是设置值没有更新为什么。我用过这个

btnClick(){
    alert('---')
  //  this.setState({data: 'nannsd'});
     this.state ={data: 'sds'};
  }

here is my code http://codepen.io/naveennsit/pen/MydPJM 这是我的代码http://codepen.io/naveennsit/pen/MydPJM

class App extends React.Component{
  constructor(){
     super();
    this.state ={data: 'test'};
  }
  btnClick(){
    alert('---')
  //  this.setState({data: 'nannsd'});
     this.state ={data: 'sds'};
  }

  render(){
    return <div>
      hello {this.state.data}
      <button onClick={this.btnClick}>click</button>
    </div>
  }

}

React.render(<App/>,document.getElementById('app'))

Two things: 两件事情:

1) Outside the constructor, you should call setState (instead of directly setting state). 1)在构造函数之外,您应该调用setState (而不是直接设置状态)。 It looks like you probably tried this since it's commented out. 看起来你可能已经尝试了这个,因为它被注释掉了。

2) You need to bind this , so that you have the right value inside btnClick . 2)你需要绑定this ,以便在btnClick有正确的值。

Here's a quick fork of your codepen with this fixed up. 这是一个快速分析你的codepen与此修复。 http://codepen.io/juliepagano/pen/xVNyrO http://codepen.io/juliepagano/pen/xVNyrO

class App extends React.Component{
  constructor(){
    super();
    this.state ={data: 'test'};
  }

  btnClick(){
    alert('---')
   this.setState({data: 'nannsd'});
     // this.state ={data: 'sds'};
  }

  render(){
    return <div>
      hello {this.state.data}
      <button onClick={this.btnClick.bind(this)}>click</button>
    </div>
  }

}

React.render(<App/>,document.getElementById('app'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM