javascript - 如何创建包装器组件并传递道具以在包装器的父级中调用它
问题描述
我有这个组件:
import React from 'react';
import PropTypes from 'prop-types';
const TableExpandedRowItem = ({ dataTitle, rowValue, cellClassProp }) => (
<div data-title={dataTitle} className={cellClassProp}>
<p>{rowValue}</p>
</div>
);
TableExpandedRowItem.propTypes = {
dataTitle: PropTypes.string.isRequired,
rowValue: PropTypes.string.isRequired,
cellClassProp: PropTypes.string,
};
TableExpandedRowItem.defaultProps = {
cellClassProp: 'cell',
};
export default TableExpandedRowItem;
当我在父级上调用它时,它非常有效,如下所示:
{rowExpanded.billingItems &&
rowExpanded.billingItems.map(
item =>
rowExpanded.id ===
item.cancellationRequestId && (
<div className="row" key={item.id}>
<TableExpandedRowItem
dataTitle={
item.billingItem.description
}
rowValue={
item.billingItem.description
}
/>
<TableExpandedRowItem
dataTitle={
item.billingItem.recurringFee
}
rowValue={
item.billingItem.recurringFee
}
/>
</div>
),
)}
但我想创建一个包装器组件。如果您看到上面的代码,则会div
包装对<TableExpandedRowItem/>
组件的调用。
所以我想做这样的事情:
import TableExpandedRowItem from './TableExpandedRowItem'
const TableExpandedRowWrapper = ({ rowClassProp }) => (
<div className={rowClassProp}>
<TableExpandedRowItem dataTitle={}/>
</div>
);
但是,如果您在第二个代码片段中看到,我将使用不同的数据调用它两次。我怎样才能在包装器组件中复制它呢?
解决方案
不确定这是否是您想要实现的目标,只需将您的键放入地图并进行另一次迭代。
注意:代码未经测试,也未经优化以避免不必要的渲染周期。
{rowExpanded.billingItems &&
rowExpanded.billingItems.map(
item =>
rowExpanded.id === item.cancellationRequestId && (
<TableExpandedRowWrapper billingItem={item.billingItem} />
),
)}
你的包装
const TableExpandedRowWrapper = ({ billingItem }) => (
<div className="row">
// alternatively iterate over Object.values(billingItem)
['description', 'recurringFee'].map(key) =>
<TableExpandedRowItem
dataTitle={
billingItem[key].description
}
rowValue={
billingItem[key].description
}
/>
)
</div>
);
rowValue
旁注:在你的例子中和你dataTitle
都是description
......似乎有点奇怪