如何在功能组件中使用 ref 访问组件的方法

bih*_*ris 1 javascript reactjs react-hooks

我正在尝试使用组件方法来访问createRef(),但是我收到了TypeError: modalRef.current is null错误。

我以前从未使用过参考文献,因此如果它错误,则会指导如何实现我想要做的事情。

这是我的尝试

const parent = () => {
  const modalRef = createRef();
  const onBtnClick = () => {
   modalRef.current.upadeState();
  }
  return(
  <div>
   <button onclick={onBtnClick}>bro</button>
    <Modal ref={modalRef} />
  </div>
 )
}
Run Code Online (Sandbox Code Playgroud)

莫代尔

export default Modal = () => {
  const upadeState = () => {
   console.log('It works fam');
   }
  return(
  <div>
    bro we here
  </div>
 )
}
Run Code Online (Sandbox Code Playgroud)

Asi*_*ora 13

为了从钩子中的父组件调用子组件方法,我们使用React.forwardRefReact.useImperativeHandle钩子。

这是调用子方法的示例。

Child.js

import React from "react";
const { forwardRef, useState, useImperativeHandle } = React;

// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Child = forwardRef((props, ref) => {
  const [state, setState] = useState(0);

  const getAlert = () => {
    alert("getAlert from Child");
    setState(state => state + 1)
  };

  // The component instance will be extended
  // with whatever you return from the callback passed
  // as the second argument
  useImperativeHandle(ref, () => ({
    getAlert,
  }));

  return (
    <>
      <h1>Count {state}</h1>
      <button onClick={() => getAlert()}>Click Child</button>
      <br />
    </>
  );
});
Run Code Online (Sandbox Code Playgroud)

父.js

import React from "react";
const { useRef } = React;

export const Parent = () => {
  // In order to gain access to the child component instance,
  // you need to assign it to a `ref`, so we call `useRef()` to get one
  const childRef = useRef();

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.getAlert()}>Click Parent</button>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

渲染子组件并使用名为 childRef 的React.useRef创建引用。我们在父组件中创建的按钮现在用于调用子组件函数childRef.current.getAlert();