【问题标题】:converting string to jsx in react native在本机反应中将字符串转换为jsx
【发布时间】:2017-07-23 17:10:49
【问题描述】:
我正在尝试将 react native 组件显示的一些文本作为字符串存储在领域数据库中。问题是文本中的某些单词需要不同的样式,因此需要包装在另一个文本标签中。例如:
<Text>
<Text> some text </Text>
<Text style={{ fontWeight: 'bold' }}>bold word</Text>
<Text> more text </Text>
</Text>
如何在存储单个单词时保留它们的样式,无论是在领域还是任何其他数据库中? IE。有没有办法在 React Native 中将字符串呈现为 jsx?
【问题讨论】:
标签:
javascript
react-native
【解决方案1】:
我认为这是不可能的,因为 JSX 在运行时没有被解析。
但是,您可以将文本存储为 html 格式并将其呈现在 WebView 中。
您可以相应地设置 WebView 的样式。
【解决方案2】:
为了渲染多色字符串,我使用了这个工具。你可以试试这样写?
import React from 'react';
import {ReactNode} from 'react';
import {Text} from 'react-native';
// In order to use this function, you need to pass strings of the type:
// 'Hello ||#FF5843|world||'
export function colorText(str: string): ReactNode {
return (
<>
{str.split('||').map((item) => {
if (item.indexOf('|') !== -1) {
const coloredText = item.split('|');
return <Text style={{color: coloredText[0]}}>{coloredText[1]}</Text>;
} else {
return item;
}
})}
</>
);
}