[进阶指南] 传送 Ref ( Day24)

传送 ref 是一种自动把 ref 从一个 component 传递到它底下的其中一个 child 的技巧。通常来说,应用程序里大部分的 component 都不需要用到它。然而,对某些种类的 component 来说它很有用,特别是能够重复使用的函式库。以下会解释最常见的情形。

有几种使用 ref 的情况:

  • 管理 focus、选择文字、或影音播放。
  • 触发即时的动画。
  • 与第三方 DOM 函式库整合。

以下一个 focus 的例子,使用 ref 触发 focus 事件:

const FormInput = React.forwardRef((props, ref) => (
  <input ref={ref} className="FancyText" type="text" id="myTextField" value={props.children} />
));

class App extends React.Component {
  
  constructor(props) {
    super(props);
    this.ref = React.createRef();
    this.focusMethod = this.focusMethod.bind(this);
  }
  
  focusMethod() {
    this.ref.current.focus()
  }
  
  render() {
    return (
      <div className="App">
        <FormInput ref={this.ref}>我是一些输入</FormInput>
        <button type="button" onClick={this.focusMethod}>点我 Focus!</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

传送 Ref 使用 API 与技术

  • 使用 React.createRef // 建立一个 ref 以透过 ref attribute 夹带在一个 React element 之上。
  • 使用 React.forwardRef // 建立一个 React component 并将 ref attribute 传递给另外一个 component
  • 在 Higher-Order Component 内传送 ref
  • 在 DevTool 里显示客制化的名称 //使用 displayName

在 DevTool 里面查看 displayName 的例子:

Codepen

Function Component && Hook useImperativeHandle 的例子

function FormInput(props, ref) {
  const inputRef = React.useRef();
  React.useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} />;
}

const FancyInput = React.forwardRef(FormInput);

function App() {
 const ref = React.useRef();
 
 function handleFocus() {
   ref.current.focus();
 }
 
 return (
   <div className="App">
     <FancyInput ref={ref} placeholder="my input" />
     <button onClick={handleFocus}>Focus</button>
   </div>
 );
}

Codepen

以上今天。

参考资料:
https://zh-hant.reactjs.org/docs/forwarding-refs.html
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
https://blog.logrocket.com/cleaning-up-the-dom-with-forwardref-in-react/


<<:  Day 26. 双向绑定语法糖 - v-model

>>:  在经营文化前,先了解现况

【7】Dataset 的三个API : Shuffle Batch Repeat 如果使用顺序不同会产生的影响

Colab连结 今天的主题比较特殊一些,要来探讨 tensorflow 中的 Dataset api...

Day 27 Azure machine learning: Schedule- Azure 为你定期执行任务

Azure machine learning: Schedule- Azure 为你定期执行任务 前...

DAY25 - 自学就像瞎子摸象,在未知的情况下试图拼出原貌

前言 记得以前在学校的时候修过资料结构与演算法,考试也都会考时间复杂度等相关的题目 毕业後,在公司上...

大共享时代系列_011_共享社区

可曾想过,我所住的社区有什麽? 什麽是社区 在本文章的定义引自 wiki_社区 提到的,因为共享共同...

Swift纯Code之旅 Day18. 「选取TableViewCell」

前言 「重复」页面的画面已经完成了,接着实作功能吧! 功能图: 实作 首先建立一个变数,用来储存Ce...