简体   繁体   English

如何在反应中将道具传递给孩子?

[英]How to pass props to a children in react?

I'm trying to pass props to a children.我正在尝试将道具传递给孩子。 Right now one of my components has a state and it's rendering other two components:现在我的一个组件有一个 state 并且它正在渲染另外两个组件:

 const [state, setState] = useState({
    plantation: {
      points: [],
      finished: false
    },
    cultures: [
      {
        culture: "",
        points: []
      }
    ]
  });

 return (
    <MoveHive>
        <PlantationMap />
    </MoveHive>
  );

In MoveHive I render the <PlantationMap> as a children using props.children and it works great.MoveHive ,我使用props.children<PlantationMap>渲染为子级,并且效果很好。

However I want to pass the state from the first component to <PlantationMap> .但是我想将state从第一个组件传递给<PlantationMap> I tried to do like regular props:我试着像普通道具一样做:

 const [state, setState] = useState({
    plantation: {
      points: [],
      finished: false
    },
    cultures: [
      {
        culture: "",
        points: []
      }
    ]
  });

 return (
    <MoveHive>
        <PlantationMap state={state} setState={setState} />
    </MoveHive>
  );

But <PlantationMap> doesn't receive the props, const { state, setState } = props;但是<PlantationMap>没有收到道具, const { state, setState } = props; , both return null. ,两者都返回 null。

How should I pass the props in this case?在这种情况下我应该如何传递道具?

I'm using Hooks, so no classes, just functions.我正在使用 Hooks,所以没有类,只有函数。

Thanks in advance提前致谢

Your approach (using regular props) is correct.您的方法(使用常规道具)是正确的。

As you can see from this sandbox , passing props does indeed work.这个沙箱中可以看出,传递道具确实有效。

Off the top, two things may go wrong in your setup:最重要的是,您的设置中可能存在两件事 go 错误:

  1. Your code has not been compiled so you are seeing stale output.您的代码尚未编译,因此您看到的是陈旧的 output。
  2. MoveHive component calls React.cloneElement on children and messes with its props. MoveHive 组件在子组件上调用React.cloneElement并弄乱了它的 props。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM