gpt4 book ai didi

javascript - 将对象数组传递给 react 组件

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:57 25 4
gpt4 key购买 nike

我创建了一个进度条组件,它接受颜色、高度、值和最大值等属性。现在它显示一个进度条,我正在尝试对进度条进行分组并按颜色对它们进行分组。这是我的组件

const ProgressBar = ({
heightSize,
value,
max,
...customProps
}) => {
const classes = classNames([
'my-ProgressBar',
{ [`my-ProgressBar--${heightSize}`]: heightSize },
customProps.className,
]);

const normalizedValue = (value / max) * 100;

return (
<progress
{...customProps}
style={{ color: customProps.color }}
className={classes}
max={100}
value={normalizedValue}
aria-valuemax={100}
aria-valuemin={0}
aria-valuenow={normalizedValue}
tabIndex="-1"
/>);
};

我正在尝试更新此组件,以便如果我将数组传递给此组件,它将返回分组的进度条。这是我失败的尝试之一。

const ProgressBar = (groups) => {
const GroupProgressBar= groups.map((group) => (
<div key={group.color}>
color: {group.color},
heightSize: {group.height},
value: {group.value},
color: {group.color}
</div>
));
return (
<progress
{...customProps}
style={{ color: group.color }}
className={classes}
max={100}
value={normalizedValue}
aria-valuemax={100}
aria-valuemin={0}
aria-valuenow={normalizedValue}
tabIndex="-1"
/>);
});

如何更新我的组件以便它可以在组中工作?

最佳答案

首先使用map为数组的每个条目创建进度条,然后从组件返回。

这样写:

const ProgressBar = ({groups, heightSize}) => {

let heightSize = 10; /*calculate here*/

const GroupProgressBar = groups.map((group, i) => (
<progress
key = {i}
{...customProps}
heightSize = {heightSize}
style={{ color: group.color }}
className={classes}
max={100}
value={group.value}
aria-valuemax={100}
aria-valuemin={0}
aria-valuenow={normalizedValue}
tabIndex="-1"
/>
)
)

return <div> {GroupProgressBar} </div>
}

检查DOCs了解更多详情。

更新:

看看我们可以从父组件传递任何 Prop , props 是一个包含所有数据的对象。在函数式组件中,我们需要这样写:

const ProgressBar = (props) => {
console.log(props);
}

这里 props 将包含传递的所有数据和方法,您可以通过 props.keyName 访问任何传递的值,从父级传递高度和组并通过 props.groups< 访问它们props.height

另一种方法是:

const ProgressBar = ({groups, heightSize}) => {
console.log(groups, heightSize);
}

这只不过是 object destructuring ,现在我们可以直接通过 groups 和 heightSize 使用这些值。

注意:为 map 内的每个进度条分配唯一的键,我使用了项目索引,但这不是一个好方法,因此从组对象中分配一些唯一的值。

关于javascript - 将对象数组传递给 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45064938/

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