react 父组件读取子组件的值

631 阅读1分钟

1,class模式下

// 父组件中
<Child diyRef={ref => this.$basicRef = ref} />
// 子组件在生命周期中
class Child extends React.Component {
    compontDidMount() {
        this.props.diyRef(this)
    }
}

在父组件中,读取this.$basicRef.读取子组件方法去获取子组件的值

2,hooks模式下,可以用 useImperativeHandle 新增的钩子,useImperativeHandle 可以让你在使用 ref 时自定义暴露给父组件的实例值。在大多数情况下,应当避免使用 ref 这样的命令式代码。useImperativeHandle 应当与 forwardRef 一起使用:

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