码迷,mamicode.com
首页 > 其他好文 > 详细

[React] Reference a node using createRef() in React 16.3

时间:2018-04-05 11:56:48      阅读:799      评论:0      收藏:0      [点我收藏+]

标签:blur   NPU   source   enc   nbsp   put   start   cti   ring   

In this lesson, we look at where we came from with refs in React. Starting with the deprecated string ref pattern, callback refs, and then how to use the new createRef() method in React 16.3.

Additional Resources: refs and the dom

 

You can use ‘React.createRef()‘ to create a ref object. Then to access it from <obj>.current.<ref_name>

import React from "react";
import { render } from "react-dom";

class App extends React.Component {
  fullName = React.createRef();

  handleBlur = () => {
    this.fullName.current.blur();
  };

  handleFocus = () => {
    this.fullName.current.focus();
  };

  render() {
    return (
      <div className="section">
        <div className="field">
          <label className="label">Full Name</label>
          <div className="control">
            <input className="input" ref={this.fullName} type="text" />
          </div>
        </div>
        <button
          className="button is-link is-outlined"
          onClick={this.handleFocus}
        >
          Focus
        </button>{" "}
        <button
          className="button is-danger is-outlined"
          onClick={this.handleBlur}
        >
          Blur
        </button>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

 

[React] Reference a node using createRef() in React 16.3

标签:blur   NPU   source   enc   nbsp   put   start   cti   ring   

原文地址:https://www.cnblogs.com/Answer1215/p/8720937.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!