React 提供三种方式创建 Refs:
- 字符串 Refs (将被废弃)
- 回调函数 Refs
- React.createRef (从React 16.3开始)
第一种方式不推荐使用,原因在此, 并且可能会在之后的版本移除。
class MyComponent extends React.Component { constructor(props) { super(props); this.toggleInputCase = this.toggleInputCase.bind(this); this.state = { uppercase: false }; } toggleInputCase() { const isUpper = this.state.uppercase; const value = this.refs.inputField.value; this.refs.inputField.value = isUpper ? value.toLowerCase() : value.toUpperCase(); this.setState({ uppercase: !isUpper }); } render() { return ( <div> {/* 创建一个字符串 ref: inputField */} <input type="text" ref="inputField" /> <button type="button" onClick={this.toggleInputCase}> Toggle Case </button> </div> ); } }
第二种方式是
return ( <div> {/* Creating a callback ref and storing it in this.inputField */} <input type="text" ref={elem => this.inputField = elem} /> <button type="button" onClick={this.toggleInputCase}> Toggle Case </button> </div> );
第三种方式 React.createRef
import React from 'react'; export default class Hello extends React.Component { constructor(props) { super(props); this.textRef = null; // 创建 ref 为 null } componentDidMount() { // 注意:这里没有使用 "current" // 直接使用原生 API 使 text 输入框获得焦点 this.textRef.focus(); } render() { // 把 inputt; ref 关联到构造器里创建的 textRef 上 return <input ref={node =>; this.textRef = node} />; } }
原文 https://zhuanlan.zhihu.com/p/64412949