如何根据选择器渲染组件X的次数?

时间:2019-03-20 14:28:41

标签: javascript reactjs

我有一个“选择”组件,用于选择我想在下面显示的表格数量。 表单是单个组件,我想重用它。它确实需要有一个独立的状态,所以我可以为同一表格(一个字段数组)使用多少个字段。关于如何使该组件呈现多个的任何提示?

const indexes = [1, 2, 3];

const MyComponent = () => {
  const [numberOfUnits, setNumberOfUnits] = useState(1);

  const Form = () => <p>my form</p>;

  return (
      <select onChange={e => setNumberOfUnits(e.target.value)}>
        {indexes.map(index => (
          <option key={index} value={index}>
            {index}
          </option>
        ))}
      </select>

    //Here I should render X (numberOfUnits) amount of times of the Form component 
  );
};

1 个答案:

答案 0 :(得分:1)

import React, { useState } from "react";
import ReactDOM from "react-dom";

const indexes = [1, 2, 3];

const MyComponent = () => {
  const [numberOfUnits, setNumberOfUnits] = useState(1);

  const Form = () => <p>my form</p>;
  const formElements = [];
  for (let i = 0; i < numberOfUnits; i++) formElements.push(<Form />);

  return (
    <React.Fragment>
      <select
        onChange={e => setNumberOfUnits(e.target.value)}
      >
        {indexes.map(index => (
          <option key={index} value={index}>
            {index}
          </option>
        ))}
      </select>
      {formElements}
    </React.Fragment>
  );
};
const rootElement = document.getElementById("root");
ReactDOM.render(<MyComponent />, rootElement);