TypeError: Cannot read property 'bind' of undefined for handleFocus
TypeError: Cannot read property 'bind' of undefined for handleFocus
出于某种原因,我不断收到
TypeError: Cannot read property 'bind' of undefined,
特别是关于 handleFocus(event)
,我不知道为什么。我检查了我的拼写,它似乎是正确的。我不知道是什么问题。这是我的代码,供您参考:
class Main extends React.Component {
constructor(props){
super(props);
this.state = {
todo: "Type in to-do item",
todos: []
};
this.handleChange = this.handleChange.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange(event){
this.setState({todo: event.target.value});
}
handleFocus(event){
this.setState({todo: ''});
}
handleSubmit(event){
const todos = this.state.todos.slice();
this.setState({
todos: todos.concat([
this.todo
]),
todo: '',
});
event.preventDefault();
}
render(){
return (
<div className = "main">
<h1>To Do App</h1>
<form>
<input type = "text" value = {this.state.todo}
onFocus= {this.handleFocus}
onChange = {this.handleChange} />
<input type = "submit" value = "Enter to-do item"
onClick = {this.handleSubmit}/>
</form>
<div className = "tasks">
<h1>Tasks</h1>
<button type="button">Clear List</button>
<button type="button">Reset List</button>
</div>
</div>
);
}
}
ReactDOM.render(
<Main />,
document.getElementById('root')
);
错误不在于 handleFocus,错误在于 handleClick。
您正在尝试将 "this" 绑定到不存在的 handleClick 函数。
注释该行可以解决问题。
// this.handleClick = this.handleClick.bind(this);
或者您需要定义handleClick函数
出于某种原因,我不断收到
TypeError: Cannot read property 'bind' of undefined,
特别是关于 handleFocus(event)
,我不知道为什么。我检查了我的拼写,它似乎是正确的。我不知道是什么问题。这是我的代码,供您参考:
class Main extends React.Component {
constructor(props){
super(props);
this.state = {
todo: "Type in to-do item",
todos: []
};
this.handleChange = this.handleChange.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange(event){
this.setState({todo: event.target.value});
}
handleFocus(event){
this.setState({todo: ''});
}
handleSubmit(event){
const todos = this.state.todos.slice();
this.setState({
todos: todos.concat([
this.todo
]),
todo: '',
});
event.preventDefault();
}
render(){
return (
<div className = "main">
<h1>To Do App</h1>
<form>
<input type = "text" value = {this.state.todo}
onFocus= {this.handleFocus}
onChange = {this.handleChange} />
<input type = "submit" value = "Enter to-do item"
onClick = {this.handleSubmit}/>
</form>
<div className = "tasks">
<h1>Tasks</h1>
<button type="button">Clear List</button>
<button type="button">Reset List</button>
</div>
</div>
);
}
}
ReactDOM.render(
<Main />,
document.getElementById('root')
);
错误不在于 handleFocus,错误在于 handleClick。
您正在尝试将 "this" 绑定到不存在的 handleClick 函数。
注释该行可以解决问题。
// this.handleClick = this.handleClick.bind(this);
或者您需要定义handleClick函数