TypeError:无法读取handleFocus的undefined属性'bind'

时间:2019-02-26 06:52:07

标签: javascript reactjs bind onfocus

出于某种原因,我继续获得

  

TypeError:无法读取未定义的属性“ bind”,

具体是关于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')
);

1 个答案:

答案 0 :(得分:0)

错误不是handleFocus,错误是handleClick。

您正在尝试将“ this”绑定到不存在的handleClick函数。

注释该行即可解决问题。

 // this.handleClick = this.handleClick.bind(this);

或者您需要定义handleClick函数