React ref

徘徊边缘 提交于 2020-02-27 15:31:23

React 组件在 加载时将 DOM 元素传入 ref 的回调函数,在卸载时则会传入 null。ref 回调会在componentDidMount 或 componentDidUpdate 这些生命周期回调之前执行。
当 ref 属性用于使用 __class 声明的自定义组件__时,ref 的回调接收的是已经加载的 React 实例

Refs 与函数式组件

你不能在函数式组件上使用 ref 属性,因为它们没有实例
ps: 可以在函数式组件内部使用 ref,只要它指向一个 DOM 元素或者 class 组件

对父组件暴露 DOM 节点

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

class Parent extends React.Component {
  render() {
    return (
      <CustomTextInput
        inputRef={el => this.inputElement = el}
      />
    );
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!