簡體   English   中英

在 React 中傳遞和使用 props

[英]Passing and using props in React

說我有以下

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

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

當我去渲染它時

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

它以道具的形式出現:道具:{}。 我怎樣才能把它作為像道具這樣的物品的對象:{名稱:'a'}? 例如。

我想要道具

     {
          name: 'a'
     }

not

     props: {...}

使用擴展運算符。

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

發生這種情況是因為屬性props被視為 JSX 屬性。 請查看react-native 文檔

當 React 看到一個代表用戶定義組件的元素時,它會將 JSX 屬性和子組件作為單個對象傳遞給該組件。 我們稱這個對象為“道具”。

在這里

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

props是此組件的 JSX 屬性和子項的單個對象。

因此,為了得到你想要的,只需修改你的組件如下

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM