Day18 Refs 和 DOM

React中若想将父层Component资料传递给子层Compontent的话,唯有使用Props方法,若需要用除此之外的方式更新作为child的DOM元素的话,就可以考虑使用ref。

ref使用时机

以下三种情况为ref建议的使用时机(参考react官网):

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

建立 Ref

使用React.createRef()便可以产生ref。Ref 常常会在一个 component 被建立出来的时候,被赋值在某个实例或DOM元素的属性中,让整个Component皆可以使用该属性。以下为官网范例:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

存取 Ref

当 ref在render中传到一个元素的时候,便可以取得ref的current参数的。
Ref 的值会根据节点的类型而有所不同:

  • 当在 HTML标签上使用 ref 参数时,使用 React.createRef() 建立 ref,便可以取得render中的DOM元素来做为它的 current 属性。
  • 当在客制化的 class component 使用 ref 参数时,ref 取得被 mount 的 component上的实例来当作他的 current属性。

HTML标签上使用 ref 参数

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // 产生一个可以储存 textInput DOM element 的 ref
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // 利用ref的「current」来找出DOM节点 
    this.textInput.current.focus();
  }

  render() {
    // 在<input>上使用ref参数
    // 和 constructor 产生的 `textInput` 连结
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

在 Class Component 加上 Ref

若想将上面的 CustomTextInput 包起来然後模拟它在被 mount 之後马上被点击,使用ref参数的话便可以取得CustomTextInput里的<input>

class AutoFocusTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();
  }

  componentDidMount() {
    this.textInput.current.focusTextInput();
  }

  render() {
    return (
      <CustomTextInput ref={this.textInput} />
    );
  }
}

<<:  第13章:分析、储存与存取系统日志介绍(一)

>>:  【D19】尝试料理#2:取得所有指数清单

基金走势再现黑色星期五?白酒股集体受挫!

近期说到基金理财,每次关於基金的消息上热搜,大多是基民都会心里一颤,觉得肯定基金又双叒叕跌了。确实,...

【资料结构】二元树的删除

说明 说明 1.根结点中的两边固定一边大另一边小。 2.下方节点当作新的根结点,继续符合一边大一边小...

【Day 21】React 关於 Hook

前言 React hook 是 React V16.8 新增的功能,它改变了 React 写 Cla...

用这9种技巧让你的部落格有个好名字

一、前言 经营部落格,会是一个长期的网路事业,在初期有许多部分我认为就应该思考好,在整个经营路上才...

[DAY 11] _软件实现I2C协议以三轴感测器为例 (ADXL345)

昨天DAY10讲了控制GPIO口来完成协议,今天来讲实际的例子,以大家最常听过三轴感测器为例,首先介...