简体   繁体   English

如何在数组中加载反应组件并显示它们

[英]How to Load a react components in an array and display them

So I have a list of components that I want to load and store in an array所以我有一个要加载并存储在数组中的组件列表

eg array = [<component1/>,<component2/>,<component3/>,]例如array = [<component1/>,<component2/>,<component3/>,]

so this is my code and how I have structed everything to work所以这是我的代码以及我如何构建一切工作

Declarations:声明:

let components = []

Loading components into array:将组件加载到数组中:

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)
   },[])

Returning components for display:返回显示组件:

return (
    <div>
     {components}
   </div>
  );
};

Somehow this code does load the component into the array but it doesn't display anything.不知何故,这段代码确实将组件加载到数组中,但它不显示任何内容。

You need to include a key for each component.您需要为每个组件包含一个key I'm fairly certain it should work once you do this (assuming the trailing } after your return is the end of the function.我相当肯定它应该在你这样做后工作(假设你return后的尾随}是函数的结尾。

For a simple key assignment:对于简单的key分配:

components[i] = <RadioButtonRN
key={i}
data={roadsigns.signs_questions[i].answers}
...
/>

try this尝试这个

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>;
}

If you want array of same components,如果你想要相同组件的数组,

return < > {
    components.map((el, i) => < Yourcomponent key = {
        i
      }
      otherParams = {
        el
      }
      />)} <
      />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM