我是 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/