gpt4 book ai didi

javascript - 使用额外的 props 将 React 组件分配给变量

转载 作者:行者123 更新时间:2023-11-30 09:25:54 27 4
gpt4 key购买 nike

我正在开发一个组件映射函数,该函数循环遍历具有 type 键的对象列表。该函数返回一个React组件类型的对象,它看起来像这样:

import _ from 'lodash';
import cellBodyTypes from './cellBodyTypes';
import {
GenericCellBody,
SubData
} from './components/CellBody';

const columnMapper = {};

_.forEach(cellBodyTypes, (type) => {
switch (type) {
case cellBodyTypes.SUB_DATA:
columnMapper[type] = SubData;
break;
case cellBodyTypes.DEFAULT:
columnMapper[type] = GenericCellBody;
break;
default:
columnMapper[type] = GenericCellBody;
}
});

export default columnMapper;

它的用法如下:

renderCellBody = (columnType, cellData, index) => {
const type = columnType || cellBodyTypes.DEFAULT;
const CellBodyComponent = columnMapper[type];

return <CellBodyComponent />;
}

渲染看起来像这样:

render (
<div>
{this.props.cellData.map((cell, index) => (
<div key={cell.id}>
{this.renderCellBody(cell.type, cell, index)}
</div>
))}
</div>
);

我想要做的是能够为新案例分配列类型,这些新案例使用与其他案例相同的 React 组件,但用附加的 props 来装饰这些新的列类型。像这样的东西:

case cellBodyTypes.NUMBER_SUB_DATA:
columnMapper[type] = React.cloneElement(SubData, {someAdditionalProp: 'something'});
break;
case cellBodyTypes.SINGLE_NUMBER:
columnMapper[type] = React.cloneElement(GenericCellBody, {someAdditionalProp: 'something'});
break;

我尝试使用React.cloneElement返回React组件的克隆,但这不起作用,因为它给了我这个错误:React.createElement:类型无效 - 预期字符串(对于内置组件)或类/函数(对于复合组件)但得到:对象。

有办法做到这一点吗?我是否接近正确的道路,只是错过了一些东西?谢谢。

最佳答案

这是因为 React.cloneElement 返回一个 React 元素,而不是组件。所以之后

columnMapper[type] = React.cloneElement(SubData,...,

columnMapper[type] 将包含一个元素。

但问题是,在 renderCellBody 函数中,您试图通过编写将元素再次转换为元素

return <CellBodyComponent />;

这会引发错误。

我建议您保留columnMapper一个元素数组。因此 switch/case 代码应该如下所示

_.forEach(cellBodyTypes, (type) => {
switch (type) {
case cellBodyTypes.SUB_DATA:
// Store element instead of component
columnMapper[type] = <SubData />;
break;
case cellBodyTypes.DEFAULT:
// Store element instead of component
columnMapper[type] = <GenericCellBody />;
break;
case cellBodyTypes.NUMBER_SUB_DATA:
columnMapper[type] = React.cloneElement(SubData, {someAdditionalProp: 'something'});
break;
case cellBodyTypes.SINGLE_NUMBER:
columnMapper[type] = React.cloneElement(GenericCellBody, {someAdditionalProp: 'something'});
break;
default:
columnMapper[type] = <GenericCellBody />;
}
});

所以现在columnMapper是一个元素数组。因此在renderCellBody函数中,不需要再次将它们转换为element。您可以简单地返回值

renderCellBody = (columnType, cellData, index) => {
const type = columnType || cellBodyTypes.DEFAULT;
const CellBodyComponent = columnMapper[type];

// CellBodyComponent is already an element. So directly return it.
return CellBodyComponent;
}

关于javascript - 使用额外的 props 将 React 组件分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49117575/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com