javascript - 如何在本机反应中将字符串转换为jsx
问题描述
我正在尝试将 javascript 字符串显示为 jsx,似乎无法在 react native 中将字符串显示为 jsx,例如const test = '<Text>hello</Text>'
render() { return ({test})}
.
给定以下字符串
const svg = '<Svg.G fill="none" fill-rule="evenodd"> <Svg.Path fill="none" d="M0 0h24v24H0z"/> <Svg.Path stroke="#333" stroke-linecap="round" stroke-linejoin="round" d="M3.5 12.5h17v9h-17zM13.5 12.5v9M10.5 12.5v9M1.883 9.602l18.353-4.918.776 2.898L2.66 12.5z"/> <Svg.Path stroke="#333" stroke-linejoin="round" d="M6 6.857c.957.553 4.675.393 4.675.393S8.957 3.945 8 3.393a2 2 0 1 0-2 3.465zM15.296 4.366c-.546.956-3.852 2.674-3.852 2.674s-.164-3.718.388-4.674a2 2 0 1 1 3.464 2z"/> <Svg.Path stroke="#333" stroke-linecap="round" stroke-linejoin="round" d="M12.508 6.755l.777 2.897M9.61 7.531l.776 2.899"/></Svg.G>';
然后我想像下面这样渲染它
render() {
return (
<View>
<Svg>
{svg}
</Svg>
</View>
);
}
这什么也不渲染,我怎样才能渲染这个字符串,或者我应该把字符串变成一个数组,然后把它渲染成一个数组?
解决方案
这不是您问题的答案,但也许它可以帮助您弄清楚如何做您想做的事情。我强烈不推荐使用这种方法;)
所以你不能只对这个字符串使用eval,因为你需要将jsx转换为js。Babel 在构建阶段为我们做这件事,但您可以解析字符串并将其转换为React.createElement形状。
仅当您知道收到的带有组件的字符串格式时,它才会起作用
我只为您的示例 ( <Text>hello</Text>
) 提供示例,因为它更容易,但它会帮助您获得一个想法。
import React, { PureComponent } from 'react';
import RN, { View } from 'react-native';
function mapStringToComponent(stringToRender) {
const parseResult = stringToRender.match(/<([a-z]*)>(.*)<\/[a-z]*>/i);
// result of this regex ["<Text>hello</Text>", "Text", "hello"]
if (parseResult !== null) {
const [, compName, innerText] = parseResult;
return React.createElement(
RN[compName],
null, // here may be an object with attributes if your node has any
innerText,
);
}
return null;
}
export default class MyDynamicComponent extends PureComponent {
render() {
const component = mapStringToComponent('<Text>hello</Text>');
return (
<View>
{component}
</View>
);
};
}
在这里您可以检查转换后的 svg 字符串的外观:babel link
我试图谷歌一些可以为你做的库,但没有找到。也许我不擅长谷歌搜索:)
推荐阅读
- mongodb - Kafka 代理关闭,因为日志目录失败
- pytorch - 用 torch.sparse 张量替换层权重
- go - 捕获按键向下/向上事件
- angular - 错误错误:在角度绑定轮播时,没有用于具有未指定名称属性的表单控件的值访问器
- amazon-web-services - 在 AWS 上进行自动缩放有什么好处?
- javascript - react-materialize 模态组件在状态更新后停止工作
- python - 您如何检查字典中的字典中是否存在值?
- kotlin - 具有自定义和默认反序列化逻辑的 Gson 类型适配器
- ssl - RabbitMQ Web-MQTT WSS 关闭客户端连接。不安全的 WS 和其他安全协议工作
- java - 与服务器的 COBOL 连接在 VSCode 中关闭