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