Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 中 父组件如何调用子组件的方法 ? #34

Open
keqing77 opened this issue Mar 25, 2024 · 1 comment
Open

React 中 父组件如何调用子组件的方法 ? #34

keqing77 opened this issue Mar 25, 2024 · 1 comment
Labels
React React 相关

Comments

@keqing77
Copy link
Owner

No description provided.

@keqing77 keqing77 added the React React 相关 label Mar 25, 2024
@keqing77
Copy link
Owner Author

keqing77 commented Apr 6, 2024

函数式组件

useImperativeHandle

useImperativeHandle 是 React 提供的一个自定义 Hook, 用于在函数组件中显式地暴露给父组件特定实例的方法

有时候我们希望在父组件中能够直接调用子组件的某些方法或访问其内部的状态。为了实现这一目的,React 提供了 useImperativeHandle 这个强大的自定义 Hook

useImperativeHandle 允许我们定义在父组件中可以直接使用的实例方法。它接收两个参数:ref 和一个回调函数,该回调函数返回一个对象,包含我们希望暴露给父组件的方法或属性

function Farther = ()= {
 const ref = useRef(null);

 return <ChildB ref={ref} />
};

const ChildB = React.forwardRef(ChildA);

function ChildA = (pops,ref) => {
  useImperativeHandle(ref,()=({
    name: "ChildA"
    log: log,
  }));
  const log = ()=>{
    console.log("子组件内部log")
  }
  return <input />
};

forwardRef

使用 forwardRef 抛出子组件的 ref

import {
  forwardRef,
  useState,
  useCallback,
  useImperativeHandle,
  createRef
} from "react";

export default function App() {
  let c = createRef(null);
  const handleChick = useCallback(() => {
    console.log("父组件点击了");
    c.current.add();
  }, [c]);
  return (
    <div className="App">
      <button onClick={handleChick}>点我运行子组件方法</button>
      <Child ref={c} />
    </div>
  );
}

const Child =  forwardRef((props, ref)=> {
  const [num, setNum] = useState(0);
  useImperativeHandle(
    ref,
    () => ({ add })
  );
  const add = () => {
    setNum((num) => ++num);
  };
  return (
    <div>
      <button onClick={add}>这是子组件自己调用</button>
      子组件的值:{num}
    </div>
  );
});

使用 forwardRef 转发 Refs 到 DOM 组件,就是将 父组件的 ref 向下传递给子组件

function Farther = ()= {
 const ref = useRef(null);

 return <ChildB ref={ref} />
};

const ChildB = React.forwardRef(ChildA);

function ChildA = (pops,ref) => {
  return <input ref={ref} />
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
React React 相关
Projects
None yet
Development

No branches or pull requests

1 participant