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

本文介绍了React中Refs的不同使用方式,从废弃的字符串Refs到回调Refs,再到React 16.3中引入的新方法createRef()。通过示例代码展示了如何创建Refs对象,并通过.current属性来访问DOM节点。
摘要由CSDN通过智能技术生成

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值