React 中的轉(zhuǎn)發(fā)ref

React V16.3? 中react引入了:

  • React.forward((props, ref) => ReactComponent) 用于將組件將refs轉(zhuǎn)發(fā)到子組件
  • React.createRef():創(chuàng)建一個(gè)ref

這2個(gè)APIs,這對父組件中訪問子組件中DOM元素提供了極大的便利

普通的使用

在當(dāng)前組件中使用ref

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />

        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

通過回調(diào)函數(shù)的形式將ref傳遞給子組件中的DOM中

回調(diào)refs

function Child(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  );
}

class Parent extends React.Component {
  
  componentDidMount() {
    if (this.textInputRef) this.textInputRef.focus();
  }

  render() {
    return (
      <Child inputRef={el => this.textInputRef = el}
    );
  }
}

將ref從父組件中轉(zhuǎn)發(fā)到子組件中的dom元素上

// FancyButton.js 子組件
import React from 'react';

// 接受props和ref作為參數(shù)
// 返回一個(gè)React 組件
const FancyButton = React.forwardRef((props, ref) => (
    <button class="fancybutton" ref={ref}>
    {props.children}
  </button>
));

export default FancyButton;


// 父組件
// app.js
class App extends React.Component {
  
  constructor(props) {
    super(props);
    // 創(chuàng)建一個(gè)ref 名字隨意
    this.ref = React.createRef();
  }
  
  componentDidMount() {
    console.log('ref', this.ref);
    // this.ref.current 表示獲取ref指向的DOM元素
    this.ref.current.classList.add('primary'); // 給FancyButton中的button添加一個(gè)class
    this.ref.current.focus(); // focus到button元素上
  }
  
  render() {
    // 直接使用ref={this.fancyButtonRef}
    return (
        <FancyButton ref={this.fancyButtonRef}>子組件</FancyButton>
    );
  }
}

在高階組件中使用轉(zhuǎn)發(fā)ref

如果使用了高階組件,還是按照上面普通的方式使用的話,會(huì)導(dǎo)致ref直接轉(zhuǎn)發(fā)到高階組件上,這很明顯是錯(cuò)的,我們只需轉(zhuǎn)發(fā)多次即可

// 高階組件
import React from 'react';

function logProps(Component) {
  class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('先前的屬性:', prevProps);
      console.log('當(dāng)前屬性:', this.props);
    }
    
    render() {
      // 使用forwardedRef作為一個(gè)ref屬性傳入組件中
      const { forwardedRef, ...rest } = this.props;
      return (
        <Component ref={forwardedRef} {...rest} />
      );
    }
  }
  
  // 使用React.forwardRef對LogProps組件進(jìn)行轉(zhuǎn)發(fā)
  return React.forwardRef((props, ref) => (
    {' 上面定義的LogProps組件接受一個(gè)forwarded屬性 '}
    <LogProps forwardedRef={ref} {...props} />
  ));
}



// FancyButton.js 子組件
import React from 'react';
import logProps from './logProps';

// 接受props和ref作為參數(shù)
// 返回一個(gè)React 組件
const FancyButton = React.forwardRef((props, ref) => (
    <button class="fancybutton" ref={ref}>
    {props.children}
  </button>
));

// 使用高階組件對其進(jìn)行封裝
export default logProps(FancyButton);


// 父組件
// app.js
class App extends React.Component {
  
  constructor(props) {
    super(props);
    // 創(chuàng)建一個(gè)ref 名字隨意
    this.ref = React.createRef();
  }
  
  componentDidMount() {
    console.log('ref', this.ref);
    // this.ref.current 表示獲取ref指向的DOM元素
    this.ref.current.classList.add('primary'); // 給FancyButton中的button添加一個(gè)class
    this.ref.current.focus(); // focus到button元素上
  }
  
  render() {
    // 直接使用ref={this.fancyButtonRef}
    return (
        <FancyButton ref={this.fancyButtonRef}>子組件</FancyButton>
    );
  }
}

可以看出如果需要使用高階組件,則在高階組件中也需要對其進(jìn)行轉(zhuǎn)發(fā)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容