1. 程式人生 > >React createRef:通過引用對象,在父組件中操作子組件

React createRef:通過引用對象,在父組件中操作子組件

commit 有一個 gets 對象 rop microsoft 一個 fault reac

一 代碼

在MyComponent中,操作其子組件(文本框)。

import React from ‘react‘;

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef(); // 將引用對象設置為父組件的成員
  }

 render() {
    return <input type="text" ref={this.inputRef} />;
 }

  componentDidMount() {
    console.log(
this.inputRef); // {current: input} console.log(this.inputRef.current); // <input type="text"> console.log(this.inputRef.current instanceof HTMLInputElement); // true this.inputRef.current.focus(); // 操作子組件 } }

二 原理

React.createRef函數會創建一個引用對象(只有一個current屬性)。

// react安裝包中的react.development.js
// an immutable object with a single mutable(易變的) value function createRef() { var refObject = { current: null }; { Object.seal(refObject); // 將對象密封(不能增刪屬性、配置屬性,但可以給屬性賦值) } return refObject; }

子組件創建完成後,會檢測其props輸入屬性中的ref屬性,並做相應的處理。

// react-dom安裝包中的react-dom.development.js
function commitAttachRef(finishedWork) { var ref = finishedWork.ref; if (ref !== null) { var instance = finishedWork.stateNode; var instanceToUse = void 0; switch (finishedWork.tag) { case HostComponent: // 原生html標簽 // 原樣返回:function getPublicInstance(instance) {return instance;} instanceToUse = getPublicInstance(instance); break; default: instanceToUse = instance; // React組件 } if (typeof ref === ‘function‘) { // ref是函數 ref(instanceToUse); // 執行 } else { // ref是引用對象 { if (!ref.hasOwnProperty(‘current‘)) { warningWithoutStack$1(         false,         ‘Unexpected ref object provided for %s. ‘           + ‘Use either a ref-setter function or React.createRef().%s‘,         getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork)); } } ref.current = instanceToUse; // 設置引用對象的current屬性 } } }

引用對象是父組件的成員,於是父組件可以通過引用對象操作子組件。

React createRef:通過引用對象,在父組件中操作子組件