简体   繁体   中英

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:

 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.

However I want to pass the state from the first component to <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; , both return null.

How should I pass the props in this case?

I'm using Hooks, so no classes, just functions.

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:

  1. Your code has not been compiled so you are seeing stale output.
  2. MoveHive component calls React.cloneElement on children and messes with its props.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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