首页 > 解决方案 > React,如何在字符串中动态创建组件?

问题描述

正如文档所示,我知道如何根据列表动态创建反应组件。但是,我想动态地创建它们,而不是一起创建它们,中间有一些字符串。具体来说,我想在一些自定义组件中包含每个正则表达式。

例如:

The cat is playing with the dog and the mouse

变成

The <animal>cat</animal> is playing with the <animal>dog</animal> and the <animal>mouse</animal>

我知道如何做正则表达式,但只是将标签添加到字符串中会使它们仍然是字符串,而不是组件。

标签: javascriptreactjs

解决方案


返回一个字符串数组和 React 组件

import React from "react";

export default function App() {
  return (
    <div>
      {"The cat is playing with the dog and the mouse"
        .split(/(cat|dog|mouse)/)
        .map((x, i) => (i % 2 ? <Animal>{x}</Animal> : x))}
    </div>
  );
}

function Animal({ children }) {
  return <span style={{ color: "red" }}>{children}</span>;
}

https://codesandbox.io/s/nice-browser-950gx


推荐阅读