Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

reactjs - Pass props from parent to children in react js

I have 2 components. The component A is the parent component:

const A = ({children}) => {

  const childrenWithProps = React.Children.map(
    children,
    (child) =>
    React.cloneElement(child, {
      test: 213
    })
  );
  return <div>{childrenWithProps}</div>
}

Here I clone the children and send to it the test prop.
The B component looks like this:

const B = () => {
    return (
        <div>
            <A>
            <div className="test">
                <MyChildrenComponent/>
            </div>
            </A>
        </div>
    );
};

export default B;

How you can see, I want to send props from A to the <MyChildrenComponent/>, but, if I try to access the props in <MyChildrenComponent/>, I get an empty object, but if I change from:

 <A>
   <div className="test">
     <MyChildrenComponent/>
  </div>
 </A>

to

 <A>
     <MyChildrenComponent/>
 </A>

...I get the props. Why if I removed the <div className="test"> the trick works but with the tag not? And how to solve the issue and to get props having this <div className="test"> wrapping my <MyChildrenComponent/> ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I see here collision between 2 different usages. In React are One-Data-Binding - possible to send data from parent to child in x nested levels also, context can specify ranges of component, which data can include.

  1. Passing Props

You can pass props as props - then it have object structure:

props{
 prop1: x
 prop2: y
 prop3: z 
}

or destructuring:

B = ({prop1, prop2, prop3}) => 

const A = ({children}) => {
  return <B name = {children}/>
}

const B = ({titleofProps}) => {
  return <B titleofProps = {children}/>
}
  1. Wrapping Component

    const Wrapper = ({children}) => {
       return (
         <>{children}</>
       );
     };
    

and:

<Wrapper>
  another code, components, etc
</Wrapper>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...