【问题标题】:React.createRef is not a function in react-railsReact.createRef 不是 react-rails 中的函数
【发布时间】:2018-05-01 19:11:36
【问题描述】:

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

【问题讨论】:

  • 你用的是最新版本的 react 吗?
  • @GautamNaik 是的

标签: javascript ruby-on-rails reactjs


【解决方案1】:

更新对 16.3 的反应 React.createRef() 这个 API 是在 react 16.3 上添加的 签出这个https://github.com/facebook/react/pull/12162

【讨论】:

    【解决方案2】:

    尝试改变这个

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

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

    不要使用 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>
        );
      }
    }
    

    【讨论】:

    • 你好@GautamNaik 谢谢你的回答。当我尝试将我的 handleClick 函数更改为您的时,我遇到了这个错误:SyntaxError: unknown: Unexpected token (7:14) 5 | } 6 | &gt; 7 | handleClick = () =&gt; { | ^ 8 | var name = this.name.current.value; 9 | console.log(name); 10 | } 当我只更改 var name = this.name.current.value; 时,我遇到了与顶部帖子中相同的错误。您的方法效果很好,但如果我需要在其他地方参考怎么办?
    • 如果你想将值发送给其他组件,你可以使用 props
    • 不,我问的是参考。我无法为任何 DOM 元素创建引用。我该如何解决?使用参考是 React.js 的思想。
    猜你喜欢
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2022-08-03
    相关资源
    最近更新 更多