javascript - 为什么 this.state 在 render() 中不起作用

标签 javascript reactjs

我是 ReactJs 的新手。我用 React 尝试了一个小片段。但是 this.state 在 ES6 ReactJs 中不起作用。帮我看看我错过了什么!!

没有 ES6 的 JS:

 var App = React.createClass({
      getInitialState: function() {
        return {value:''};
      },

      handleClick: function(e){
        this.setState({value:e.target.value});
        console.log(this.state.value);//getting value here
      },
      render: function() {
        return(
          <div>
            Hello {this.props.name}
            <input type="text" onChange={this.handleClick}/>
            {this.state.value}// no value
          </div>);
      }
    });
    React.render(<App name="Praveen" />, document.getElementById('content'));

这个案例工作正常。 Jsbin code

带有 ES6 的 JS:

class App extends React.Component {
  constructor(props){
    super(props)
    this.state ={value:''};
  }
  handleClick(e){
    this.setState({value:e.target.value});
    console.log(this.state.value);//getting value here
  }
  render() {
    return(
      <div>
        Hello {this.props.name}
        <input type="text" onChange={this.handleClick}/>
        {this.state.value}// no value
      </div>);
  }
}
React.render(<App name="Praveen" />, document.getElementById('content'));

在这种情况下,无论何时我设置 this.setState() 渲染函数都不会被调用。 Jsbin code

最佳答案

ES6 中的 React 移除了 this 的自动绑定(bind),这意味着在扩展 React.Component 的类上声明的函数必须 .bind(this) 显式或使用箭头函数语法。

<input type="text" onChange={this.handleClick.bind(this)} />

class App extends React.Component {
   handleClick = (e) => {}
}

关于javascript - 为什么 this.state 在 render() 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32850288/

相关文章:

javascript - 如何使用自定义帖子类型创建 WordPress 视频库

javascript - 根据条件是否 react 更改文本颜色

reactjs - React & Service Worker - 缓存内容 - 通知用户

javascript - 我们可以将类保存在变量中并将目标元素与该变量一起保存吗?

javascript - 从字符串序列中获取 n 对

javascript - Ember 反向对象无法正常工作

javascript - react 16.14.0 : Error was not caught ReferenceError: exports is not defined

reactjs - VSCode 不会在 typescript 中导入 <Text> 组件

javascript - 在哪里/如何存储数据集合

javascript - 如何从表单提交中获取所有单选按钮组选择