ReactJS onChange函数

时间:2017-01-25 15:19:37

标签: javascript reactjs web react-native onchange

我的onChange功能在哪里出错了?我希望能够输入我的文本框,但是当我重新编译时,我一直收到以下控制台错误:

**Uncaught TypeError: Cannot read property 'value' of undefined**

见下面的代码:

var name = "";
export default React.createClass({

  handleChange: function() {
    this.props.onUserInput(
        this.refs.name.value    
    )
  },

  render() {
    return (
      <div>
        <div>{this.props.children}</div>
        <Well style={style.well}>
          <div style={style.userContent}>

            <input style={style.userDetails} 
                   id ="userName" 
                   type="text" 
                   onChange={this.handleChange()} 
                   value ={name} />

              <Button bsStyle="primary">Update</Button>
          </div>
        </Well>         
      </div>
    );
  }
});

2 个答案:

答案 0 :(得分:2)

()。移至onChange,您必须将参考传递给

onChange={ this.handleChange } 

更新:

此外,在这种情况下,您不需要refs,因为您可以获得这样的价值

handleChange: function (event) {
  this.props.onUserInput(
    event.currentTarget.value    
  )
},

根据您的示例,我看到您使用变量name,这是不好的做法,我认为在这种情况下您可以使用state,就像在我的示例中一样

const App = React.createClass({
  getInitialState: function () {
    return {
      value: ''
    }
  },
  
  handleChange: function (event) {
    this.setState({
      value: event.currentTarget.value
    }, () => { // arrow function, ES2015
      console.log(this.state.value);
      // call this.props.onUserInput(this.state.value)
    });
  },

  render() {
    return (
      <input style={ {} } 
        id="userName" 
        type="text" 
        onChange={ this.handleChange } 
        value={ this.state.value } 
      />
    );
  }
});

ReactDOM.render(<App />, document.getElementById('root'))
<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="root"></div>

答案 1 :(得分:0)

嗯,有两件事正在发生。

首先,this.refs.nameundefined,您无法读取value的属性undefined(如错误所示)。您从未在ref方法中创建render()。阅读React docs on the ref attribute以更好地了解其工作原理以及固有的局限性。

其次,您正在调用 handleChange函数,而不仅仅是传递给onChange

onChange={this.handleChange()} // you CALL the function with ()

相反,直接传递它:

onChange={this.handleChange}

请注意,如果您切换到ES6 class组件,则还需要绑定该函数(否则this运行undefined时将handleChange:< / p>

onChange={this.handleChange.bind(this)}

目前,React.createClass正在为你做绑定。