javascript - 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>
我知道如何做正则表达式,但只是将标签添加到字符串中会使它们仍然是字符串,而不是组件。
解决方案
返回一个字符串数组和 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>;
}
推荐阅读
- php - 如何获取 Stripe 付款唯一标识符以保存在数据库中
- java - JodaTime:日期时间用 Z 代替 -04:00
- android - 在浏览器中打开 PDF
- python - 使用部分 JSON 值作为行标题将 JSON 转换为 CSV
- angular - 反应式表单值是类型 { "value" : "therealname"} 的对象,而不仅仅是 "therealname"
- python - 无法在多维列表中使用 .strip()
- python - 选择最佳分段回归拟合时代码太慢
- jquery - 在 Chrome 上加载 jQuery CDN 会给出“加载资源失败:net::ERR_CERT_AUTHORITY_INVALID”
- db2 - Informatica DB2 DSN 在 Designer 中不工作
- javascript - Bokeh 如何使用 ajax 更新数据源处理日期时间