获取错误无法读取未定义的属性“setState" [英] Getting error Cannot read property 'setState' of undefined
问题描述
我是 Reactjs 的新手.我正在尝试做一些非常简单的事情:当用户更改文本区域内的文本时,更新渲染函数内的 div.有什么建议么?
class HTMLEditor extends React.Component {构造函数(道具){超级(道具);this.state = {value: '把 HTML 放在这里'};}句柄变化(e){this.setState({value: e.currentTarget.value});}使成为() {返回 (<div><textarea defaultValue={this.state.value} onChange={ this.handleChange }/><div>{this.state.value}</div>
);}}ReactDOM.render(<HTML 编辑器/>,document.getElementById('容器'));
你应该绑定 handleChange
函数.您收到此错误是因为,在您的 handleChange 函数 this
中,keywork 未引用 React 类的上下文,因此您需要绑定该函数.
class HTMLEditor extends React.Component {构造函数(道具){超级(道具);this.state = {value: '把 HTML 放在这里'};}handleChange = (e) =>{this.setState({value: e.currentTarget.value});}使成为() {返回 (<div><textarea defaultValue={this.state.value} onChange={ this.handleChange }/><div>{this.state.value}</div>
);}}ReactDOM.render(<HTML 编辑器/>,document.getElementById('容器'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="container"></div>
I'm new with Reactjs. I'm trying to do something very simple: update a div inside a render function when the user change the text inside text area. Any suggestions?
class HTMLEditor extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'Put here HTML'};
}
handleChange(e) {
this.setState({value: e.currentTarget.value});
}
render() {
return (
<div>
<textarea defaultValue={this.state.value} onChange={ this.handleChange } />
<div>{this.state.value}</div>
</div>
);
}
}
ReactDOM.render(
<HTMLEditor />,
document.getElementById('container')
);
You should bind the handleChange
function. You are getting this error because, in your handleChange function this
keywork doesn't refer to the context of the React Class and hence you need to bind the function.
See this answer on why do you need to bind event handlers in React
class HTMLEditor extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'Put here HTML'};
}
handleChange = (e) =>{
this.setState({value: e.currentTarget.value});
}
render() {
return (
<div>
<textarea defaultValue={this.state.value} onChange={ this.handleChange } />
<div>{this.state.value}</div>
</div>
);
}
}
ReactDOM.render(
<HTMLEditor />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
这篇关于获取错误无法读取未定义的属性“setState"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!