最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React.createRef is not a function in react-rails - Stack Overflow

programmeradmin5浏览0评论

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

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).

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

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).

Share Improve this question asked May 1, 2018 at 19:11 Herman EydHerman Eyd 1091 gold badge1 silver badge10 bronze badges 2
  • are u using latest version of react? – Gautam Naik Commented May 1, 2018 at 19:14
  • @GautamNaik yes – Herman Eyd Commented May 1, 2018 at 19:34
Add a ment  | 

2 Answers 2

Reset to default 13

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

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

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>
    );
  }
}
发布评论

评论列表(0)

  1. 暂无评论