React.createRef不是react-rails中的函数

时间:2018-05-01 19:11:37

标签: javascript ruby-on-rails reactjs

我在ruby on rails项目中使用react-rails gem。我尝试添加对DOM元素的引用。这是我的组成部分:

class NewItem extends React.Component {
  constructor(props) {
    super(props);
    this.name = React.createRef();
  }
  handleClick() {
    var name  = this.name.value;
    console.log(name);
  }
  render() {
    return (
      <div>
        <input ref={this.name} placeholder='Enter the name of the item' />
        <button onClick={this.handleClick}>Submit</button>
      </div>
    );
  }
};

当我尝试在浏览器中加载页面时,我在控制台中有此消息: TypeError: React.createRef is not a function. (In 'React.createRef()', 'React.createRef' is undefined)

2 个答案:

答案 0 :(得分:8)

更新响应16.3 React.createRef()在API 16.3上添加了此API 结帐https://github.com/facebook/react/pull/12162

答案 1 :(得分:-2)

尝试更改此

  handleClick = () => {
    var name  = this.name.current.value;
    console.log(name);
  }

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

不要使用ref来获取输入值。使用此方法

{{1}}