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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50122421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:55:48  来源:igfitidea点击:

React.createRef is not a function in react-rails

javascriptruby-on-railsreactjs

提问by Herman Eyd

A am using react-rails gem in my ruby on rails project. I try to add reference to my DOM element. This is my component:

我在我的 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>
    );
  }
};

When i try to load the page in browser i have this message in console: TypeError: React.createRef is not a function. (In 'React.createRef()', 'React.createRef' is undefined).

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

回答by u8652529

update react to 16.3 React.createRef() this API is added on react 16.3 checkout this https://github.com/facebook/react/pull/12162

更新反应到 16.3 React.createRef() 这个 API 是在反应 16.3 结帐时添加的https://github.com/facebook/react/pull/12162

回答by Gautam Naik

Try changing this

尝试改变这个

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

to

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

Dont use ref for getting value of input. Use this method

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

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>
    );
  }
}