" ReferenceError:未定义getInput"反应输入元素

时间:2017-01-20 04:10:57

标签: javascript reactjs ecmascript-6

class HelloWorldComponent extends React.Component {
  constructor() {
    super()
    this.getInput = this.getInput.bind(this)
  }
  getInput() {
    alert('focused');
  }
  render() {
    return (      
      <input type="text" onFocus={getInput}/>    
    );
  }
}

ReactDOM.render(
  <HelloWorldComponent/>,
  document.getElementById('react_example')
);

这段代码有什么问题?无法触发警报,我得到的getInput未定义错误。

http://jsbin.com/qoduyawaci/1/edit

3 个答案:

答案 0 :(得分:4)

您忘记添加正确的参考。使用 this.getInput 代替 getInput

像这样

class HelloWorldComponent extends React.Component {
  constructor() {
    super()
    this.getInput = this.getInput.bind(this);
  }
  getInput() {
    alert('focused');
  }
  render() {
    return (      
      <input type="text" onFocus={this.getInput}/>    
    );
  }
}

ReactDOM.render(
  <HelloWorldComponent/>,
  document.getElementById('react_example')
);

答案 1 :(得分:1)

您应该使用this.getInput代替getInput

http://jsbin.com/nehadisuvu/1/edit?html,js,output

答案 2 :(得分:0)

使用this.getInput来调用该函数。 您也可以使用 ES6 中的箭头功能来避免绑定。

getInput = () => {
    alert('focused');
 }

你可以避免

this.getInput = this.getInput.bind(this)

在构造函数中。这是正确的ES6方法。

http://jsbin.com/sebotirito/1/edit?html,js,output