简体   繁体   中英

Passing and using props in React

Say I had the following

const Obj = [
     {
          name: 'a'
     },
     {
          name: 'b'
     }
]

const RenderSomeObj = props => {
     console.log('props', props)
     return null
}

When I go to render it with

{Obj.map((item, index) => (
    <RenderSomeObj props={item} />
))

It comes out as props: props: {}. how can I get it as just the object that is item like props: { name: 'a'}? eg.

I want props to be

     {
          name: 'a'
     }

not

     props: {...}

Use the spread operator.

{Obj.map((item, index) => (
    <RenderSomeObj {...item} />
))

This happens because the attribute props is regarded as a JSX attribute. Please take a look on the react-native documentation

When React sees an element representing a user-defined component, it passes JSX attributes and children to this component as a single object. We call this object “props”.

In here

const RenderSomeObj = props => {
     console.log('props', props)
     return null
}

props is the single object of the JSX attributes and children to this component.

Therefore, to get what you want, simply modify your component as below

 const RenderSomeObj = props => {
     console.log('props', props.props)
     return null
  }

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