NextJs、React,通过两个组件传递数据

NextJs, React, passing data through two components

我的 child 组件中有一个变量,用于保存其高度数据。我需要通过它的 parent 传递它并进入 parent 的 parent。我可以将它传递给 parent,但不明白为什么传递给 parent 的 parent 不起作用。我得到的错误是:

Unhandled Runtime Error
TypeError: props.func is not a function

Source
components\layout.js (22:10) @ Object.pull_data [as func]

  20 |  const navHeight = data;
  21 |   console.log(navHeight); 
> 22 |   props.func(navHeight);

  24 | }

Child分量:

export default function Navbarmain(props) {

  const ref = useRef();
  useEffect(() => {
    const navHeight = ref.current?.clientHeight;
    props.func(navHeight);
  }, []);


  return (
    <div ref={ref}>

Child的parent:

export default function Layout({ children, home }, props) {

  const pull_data = (data) => {

   const navHeight = data;
    console.log(navHeight); // Correctly outputs Height of child component
    props.func(navHeight);  // Attempt to do a repeat of what I just did

  }

  return (
    <div className={styles.layoutWrap}>
      <Navbarmain func={pull_data}></Navbarmain>

Parent的parent:

export default function Home({ allPostsData }) {
      const pull_data = (data) => {
    
        const navHeight = data;
         console.log(navHeight); 
    
       }
     
    
    
      return (
        <div>
          <Layout home func={pull_data}>

问题出在 Child's parent' 的组件道具中。您正在将大括号内的道具与 props ({ children, home }, props) 混合使用。如果您以这种方式重构,它将毫无问题地工作

https://codesandbox.io/embed/fervent-cohen-td6sig?fontsize=14&hidenavigation=1&theme=dark

export default function Layout({ children, home, func }) {

  const pull_data = (data) => {

   const navHeight = data;
    console.log(navHeight); // Correctly outputs Height of child component
    func(navHeight);  // Attempt to do a repeat of what I just did

  }

  return (
    <div className={styles.layoutWrap}>
      <Navbarmain func={pull_data}></Navbarmain>