[英]How can I pass props to a component received from parent as a prop?
import React from 'react'
const fruits = [
{ id: 1, text: `mango` },
{ id: 2, text: `apple` },
]
const Fruit = ({ fruit }) => (
<div>{ fruit.id } - { fruit.name }</div>
)
const Fruits = ({ component }) => (
<ul>
{ fruits.map( fruit => <li>{ component({ fruit }) }</li> ) }
</ul>
)
export const Parent = () => (
<div>
<Fruits component={ <Fruit /> } />
</div>
)
如上例所示,無法從父級傳遞道具,因為道具是從在子級中循環的對象數組中獲得的。
當我運行此代碼時,它顯然會引發錯誤:
類型錯誤:組件不是函數
我該如何處理?
有幾個選項:
import React, { cloneElement } from "react";
export const Parent = () => (
<div>
<Fruits component={<Fruit />} />
</div>
);
const Fruits = ({ component }) => (
<ul>
{fruits.map((fruit) => (
<li>{cloneElement(component, { fruit })}</li>
))}
</ul>
);
我通常會避免這樣做。 cloneElement確實有一些用處,但不常用,所以可能不熟悉,難以理解和維護。 另外,我認為您的方案有更好的選擇:
export const Parent = () => (
<div>
<Fruits component={Fruit} />
</div>
);
const Fruits = ({ component: Component }) => (
<ul>
{fruits.map((fruit) => (
<li>
<Component fruit={fruit} />
</li>
))}
</ul>
);
這很簡單,但它確實使兩個組件緊密耦合。 Parent 和 Fruits 需要在同一頁面上確切地知道哪些 props 將被發送到另一個組件。 如果您使用它的方法數量有限,我會使用這種方法,因此您不介意它不是很靈活。
export const Parent = () => (
<div>
<Fruits component={(props) => <Fruit fruit={props.fruit} />} />
</div>
);
const Fruits = ({ component }) => (
<ul>
{fruits.map((fruit) => (
<li>{component({ fruit })}</li>
))}
</ul>
);
這減少了組件之間的耦合,因為 Fruits 不再假設子組件的 props 的名稱是什么。 這種方法通常被稱為“渲染道具” 。 如果您需要更高級別的靈活性,我會使用這種方法。
嘗試這個
const Fruits = ({ component }) => (
<ul>
{ fruits.map( f => <li><component fruit={</f>} ></li> ) }
</ul>
)
import React from 'react'
const Base = ({ item }) => (
<li>{ item.id } - { item.name }</li>
)
const BaseItems = ({ items }) => (
<ul>
{ items.map((item, i) => <Base key={i} item={item} /> ) }
</ul>
)
const fruits = [
{ id: 1, text: `mango` },
{ id: 2, text: `apple` },
]
const vegetables = [
{ id: 1, text: `potato` },
{ id: 2, text: `broccoli` },
]
export const Parent = () => (
<div>
<BaseItems items={fruits} />
<BaseItems items={vegetables} />
</div>
)
您可以簡單地嘗試一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.