[英]How to Load a react components in an array and display them
所以我有一個要加載並存儲在數組中的組件列表
例如array = [<component1/>,<component2/>,<component3/>,]
所以這是我的代碼以及我如何構建一切工作
聲明:
let components = []
將組件加載到數組中:
useEffect(() => {
for(let i=0;i<length;i++){
components[i] = <RadioButtonRN
data={roadsigns.signs_questions[i].answers}
box={false}
textColor={primary}
initial={2}
selectedBtn={(e) => selectedAnswer(e)}
/>
}
connsole.log(components)
},[])
返回顯示組件:
return (
<div>
{components}
</div>
);
};
不知何故,這段代碼確實將組件加載到數組中,但它不顯示任何內容。
您需要為每個組件包含一個key
。 我相當肯定它應該在你這樣做后工作(假設你return
后的尾隨}
是函數的結尾。
對於簡單的key
分配:
components[i] = <RadioButtonRN
key={i}
data={roadsigns.signs_questions[i].answers}
...
/>
嘗試這個
import React from "react";
function App() {
const compArray = () => {
let arr = [];
for (let i = 0; i < 3; i++) {
arr.push(<Name />);
}
return arr;
};
return <>{compArray()}</>;
}
export default App;
function Name() {
return <h1>Hello world </h1>;
}
如果你想要相同組件的數組,
return < > {
components.map((el, i) => < Yourcomponent key = {
i
}
otherParams = {
el
}
/>)} <
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.