简体   繁体   中英

React, how to pass known properties and props.children

Question on how to pass properties into React methods. Probably a very easy question asked before but since I don't know how to articulate it properly, do bear with me and feel free to point me to the duplicate.

I'd like to use some known properties and prop.children of a React component at the same time, how do I pass them into my React methods?

For example, I know to pass a known property into React method component we do this:

export const SomeComponent = ({prop1, prop2}) =>{ ... do something with prop1 and prop2 }

And the to use prop.children we need to do this:

export const SomeComponent = (props) =>{ ... then some tags wrapping {props.children}... }

And now I have a function that I need both prop1 and prop2 and also the props.children. How should I construct the syntax to realize this need?

ie essentially using it as:

<SomeComponent prop1={value1} prop2={value2}>
   <NestedComponent />
</SomeComponent>
const MyComp = props => {
  const {prop1, children} = props;
  // do something with props
  // do something with prop1
  // do something with children
  return (<div>{children}</div>);
}

The ({prop1, prop2}) syntax is a destructuring assignment introduced in ES6. Actually what the function get is an object containing keys prop1 , prop2 , like this

{
  prop1: ...,
  prop2: ...,
  ...,
}

You can read this for more detail: Unpacking fields from objects passed as a function parameter .

Hence, when passing both prop1, prop2, and children, you can use either syntax below:

  • With destructuring assignment:
     export const SomeComponent = ({prop1, prop2, children}) => {... do something with prop1, prop2, and children }
  • Without destructuring assignment:
     export const SomeComponent = (props) => {... do something with props.prop1, props.prop2, and props.children }

you can do something like this -

<SomeComponent  prop1={} prop2={}>
  <div> test </div>
</SomeComponent>

 export const SomeComponent = (props) =>{ ...access the prop1 as props.prop1 and prop2 
 as props.prop2 and children like props.children }

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