gpt4 book ai didi

javascript - 如何连接 Prop

转载 作者:行者123 更新时间:2023-11-30 13:52:06 28 4
gpt4 key购买 nike

假设我必须将 div 和 Prop 分开。我需要将 Prop 传播到两个单独的 div。给定函数:

function Collection(props) {
const coll = props.coll
const coll_list = coll.map((coll, index) => {
return (
<span key={index}>{coll}</span>
)
})

return (
<div className="main_div">
<div className="div_a">
{coll_list}
</div>
<div className="div_b">
{coll_list}
</div>
</div>
)
}

结果应该是这样的:

<div className="main_div">
<div className="div_a">
<span>item_1</span>
<span>item_2</span>
<span>item_3</span>
</div>
<div className="div_b">
<span>item_4</span>
<span>item_5</span>
<span>item_6</span>
</div>
</div>

我会很感激所有的答案。谢谢。

最佳答案

如果你只需要拆分为 2 个列表,那么你可以找到中间并将数组拆分为 2 个部分:

function Collection(props) {
const coll = props.coll.map((coll, index) => (<span key={index}>{coll}</span>));
const middle = Math.floor(coll.length / 2);
const coll_list_a = coll.slice(0, middle);
const coll_list_b = coll.slice(middle, coll.length);

return (
<div className="main_div">
<div className="div_a">
{coll_list_a}
</div>
<div className="div_b">
{coll_list_b}
</div>
</div>
)
}

如果您想要一个更健壮的解决方案来拆分为长度为 n 的部分,您可以将数组切成 block 并动态创建列表:

function chunkify(arr, n){
let index = 0;
const len = arr.length;
const chunks = [];

for (index = 0; index < len; index += n) {
chunks.push(arr.slice(index, index + n));
}

return chunks;
}

function Collection(props) {
const coll = props.coll.map((coll, index) => (<span key={index}>{coll}</span>));
const chunks = chunkify(coll)

return (
<div className="main_div">
{
chunks.map((list, index) => (
<div key={index} className={"div_" + index}>
{list}
</div>
))
}
</div>
)
}

关于javascript - 如何连接 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58039205/

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