如何使用道具制作反应 js 元素?

How to make a react js element by using props?

我在 React js 中有一个像这样的功能元素,

function FilterOptions() {
  const [isShown, setIsShown] = useState(false);
  return (
    <div className="filter__options">
      {["Category", "Design", "Size", "Style"].map((ourOption) => (
        <div
          onMouseEnter={() => setIsShown(true)}
          onMouseLeave={() => setIsShown(false)}
          className="filter__options__container"
        >
          <div className="filter__options__button">
            {ourOption}
          </div>
          {isShown && <div className="filter__options__content">  Here I want to return the element using props </div>}
        </div>
      ))}
    </div>
  );
}

我创建了一个名为 Category.js、Design.js、Size.js、Style.js 的文件。 现在我想使用道具,这样我就可以像这样连接 <{ourOption}> <{ourOption}/> 这样就可以 return 元素。 知道怎么做吗?

您可以遍历组件数组而不是字符串

{[Category, Design, Size, Style].map((Component) => (
    <Component/>
);

Choosing the Type at Runtime

首先:导入使用的组件并创建一个查找对象

import Category from 'Category';
import Design from 'Design';
import Size from 'Size';
import Style from 'Style';
// ... other imports

const components = {
  Category,
  Design,
  Size,
  Style,
  // ... other mappings
};

其二:查找要渲染的组件

function FilterOptions() {
  const [isShown, setIsShown] = useState(false);
  return (
    <div className="filter__options">
      {["Category", "Design", "Size", "Style"].map((ourOption) => {
        const Component = components[ourOption];
        return (
          ...
            <div className="filter__options__button">
              <Component />
            </div>
          ...
        ))}}
    </div>
  );
}

或者,您可以直接在要映射的数组中导入并指定它们。

function FilterOptions() {
  const [isShown, setIsShown] = useState(false);
  return (
    <div className="filter__options">
      {[Category, Design, Size, Style].map((Component) => (
        ...
          <div className="filter__options__button">
            <Component />
          </div>
        ...
      ))}
    </div>
  );
}

我会这样做 react document

//create components array
const components = {
    photo: Category,
    video: Design
    .....
};

{
    Object.keys(components).map((compName) => {
        const SpecificSection = components[compName];
        return <SpecificSection />;
    })
}

这是一个您可以使用的小示例代码。使用直接组件而不是尝试通过字符串来确定。

const Comp1 = () => {
  return <p>Comp1 Here</p>
}

const Comp2 = () => {
  return <p>Comp 2 Here</p>
}

export default function App() {
  return (
    <div className="App">
      {[Comp1, Comp2].map(Komponent => { 
        // use Komponent to prevent overriding Component
        return <Komponent></Komponent>
      })}
    </div>
  );
}