在 < Text > 字段中为单个单词添加粗体或斜体

如何在文本字段中使用粗体或斜体表示一个单词:

<Text>This is a sentence <b>with</b> one word in bold</Text>

如果我为粗体字创建一个新的文本字段,它会将其分隔到另一行,所以这肯定不是正确的方法。这就像在一个 < p > 标记中创建一个 < p > 标记,只是为了加粗一个单词。

183771 次浏览

您可以将 <Text>用作其他文本组件的容器。 这是一个例子:

...
<Text>
<Text>This is a sentence</Text>
<Text style=\{\{fontWeight: "bold"}}> with</Text>
<Text> one word in bold</Text>
</Text>
...

这是 例子

更像网页的感觉:

const B = (props) => <Text style=\{\{fontWeight: 'bold'}}>{props.children}</Text>
<Text>I am in <B>bold</B> yo.</Text>

用这个 反应本地库反应本地库

安装

npm install react-native-htmlview --save

基本用法

 import React from 'react';
import HTMLView from 'react-native-htmlview';


class App extends React.Component {
render() {
const htmlContent = 'This is a sentence <b>with</b> one word in bold';


return (
<HTMLView
value={htmlContent}
/>    );
}
}

支持几乎所有的 html 标记。

用于更高级的用途,如

  1. 链接处理
  2. 自定义元素渲染

查看此 自述

你可以使用 https://www.npmjs.com/package/react-native-parsed-text

import ParsedText from 'react-native-parsed-text';
 

class Example extends React.Component {
static displayName = 'Example';
 

handleUrlPress(url) {
LinkingIOS.openURL(url);
}
 

handlePhonePress(phone) {
AlertIOS.alert(`${phone} has been pressed!`);
}
 

handleNamePress(name) {
AlertIOS.alert(`Hello ${name}`);
}
 

handleEmailPress(email) {
AlertIOS.alert(`send email to ${email}`);
}
 

renderText(matchingString, matches) {
// matches => ["[@michel:5455345]", "@michel", "5455345"]
let pattern = /\[(@[^:]+):([^\]]+)\]/i;
let match = matchingString.match(pattern);
return `^^${match[1]}^^`;
}
 

render() {
return (
<View style={styles.container}>
<ParsedText
style={styles.text}
parse={
[
{type: 'url',                       style: styles.url, onPress: this.handleUrlPress},
{type: 'phone',                     style: styles.phone, onPress: this.handlePhonePress},
{type: 'email',                     style: styles.email, onPress: this.handleEmailPress},
{pattern: /Bob|David/,              style: styles.name, onPress: this.handleNamePress},
{pattern: /\[(@[^:]+):([^\]]+)\]/i, style: styles.username, onPress: this.handleNamePress, renderText: this.renderText},
{pattern: /42/,                     style: styles.magicNumber},
{pattern: /#(\w+)/,                 style: styles.hashTag},
]
}
childrenProps=\{\{allowFontScaling: false}}
>
Hello this is an example of the ParsedText, links like http://www.google.com or http://www.facebook.com are clickable and phone number 444-555-6666 can call too.
But you can also do more with this package, for example Bob will change style and David too. foo@gmail.com
And the magic number is 42!
#react #react-native
</ParsedText>
</View>
);
}
}
 

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
 

url: {
color: 'red',
textDecorationLine: 'underline',
},
 

email: {
textDecorationLine: 'underline',
},
 

text: {
color: 'black',
fontSize: 15,
},
 

phone: {
color: 'blue',
textDecorationLine: 'underline',
},
 

name: {
color: 'red',
},
 

username: {
color: 'green',
fontWeight: 'bold'
},
 

magicNumber: {
fontSize: 42,
color: 'pink',
},
 

hashTag: {
fontStyle: 'italic',
},
 

});

粗体字:

<Text>
<Text>This is a sentence</Text>
<Text style=\{\{fontWeight: "bold"}}> with</Text>
<Text> one word in bold</Text>
</Text>

斜体文字:

<Text>
<Text>This is a sentence</Text>
<Text style=\{\{fontStyle: "italic"}}> with</Text>
<Text> one word in italic</Text>
</Text>

您可以使用所需的样式来嵌套 Text 组件。该样式将与第一个 Text 组件中已定义的样式一起应用。

例如:

 <Text style={styles.paragraph}>
Trouble singing in. <Text style=\{\{fontWeight: "bold"}}> Resolve</Text>
</Text>

嵌套文本组件现在是不可能的,但是您可以像下面这样将文本封装在视图中:

<View style=\{\{flexDirection: 'row', flexWrap: 'wrap'}}>
<Text>
{'Hello '}
</Text>
<Text style=\{\{fontWeight: 'bold'}}>
{'this is a bold text '}
</Text>
<Text>
and this is not
</Text>
</View>

我使用了括号内的字符串来强制单词之间的空格,但是您也可以使用右边缘或左边缘来实现它。希望能有帮助。

比如说!

const TextBold = (props) => <Text style=\{\{fontWeight: 'bold'}}>Text bold</Text>

< 文字 > 123 < TextBold/>

enter image description here

我是 本机可跨越字符串的维护者

具有自定义风格的嵌套 <Text/>组件工作良好,但可维护性较低。

我建议您使用这个库构建这样的可跨越字符串。

SpannableBuilder.getInstance({ fontSize: 24 })
.append('Using ')
.appendItalic('Italic')
.append(' in Text')
.build()
<Text>
<Text style=\{\{fontWeight: "bold"}}>bold</Text>
normal text
<Text style=\{\{fontStyle: "italic"}}> italic</Text>
</Text>

它不在要求的文本字段中,而是将单独的文本元素包装到视图中,从而得到所需的输出。如果您不想在项目中添加另一个库,只是为了设置一些文本的样式,那么可以使用这种方法。

<View style=\{\{flexDirection: 'row'}}>
<Text style=\{\{fontWeight: '700', marginRight: 5}}>Contact Type:</Text>
<Text>{data.type}</Text>
</View>

结果如下

enter image description here

您还可以将 Text 标记放在另一个 Text 标记中。第二个文本标记将继承第一个文本标记的样式,但是您保留了独立于其父标记对其进行样式设置的能力。

<Text style={styles.bold}>Level:
<Text style={styles.normal}>Easy</Text>
</Text>


//in your stylesheet...


bold: {
fontSize: 25,
fontWeight: "bold",
color: "blue",
},
normal: {
// will inherit size and color attributes
fontWeight: "normal",
}


这招对我很管用

<h2>
{`Step ${activeStep+1}/3 - `} <strong>{stepName}</strong>
</h2>

//输出步骤1/3-信息

似乎有一个或两个组件像 反应-原生-标记-文本,但如果你不介意使用正则表达式解析 很小标记。

零食展示

import * as React from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';


/**
* @typedef MiniMarkupTextProps
* @type {object}
* @property {string|null|undefined} text - a piece of mini markup text.
* @property {object|null|undefined} itemStyle - itemStyle;
*/
export default React.memo((/** @type {MiniMarkupTextProps} */ props) => {
const markup = props.text;
const mappings = new Map([
[
'p',
(text, index) => {
return (
<Text key={index} style={props.itemStyle}>
{text}
</Text>
);
},
],
[
'b',
(text, index) => {
return (
<Text key={index} style={[{ fontWeight: 'bold' }, props.itemStyle]}>
{text}
</Text>
);
},
],
]);
const keys = Array.from(mappings.keys());
const regExp = new RegExp(
`(${keys.map((e) => `<${e}>`).join('|')})(.*?)(${keys
.map((e) => `<\\/${e}>`)
.join('|')})|(\\s*)`,
'g'
);


return (
<Text>
{markup?.match(regExp)?.map(function (tag) {
const isEmpty = tag.trim().length === 0;
return isEmpty ? (
<Text>&nbsp;</Text>
) : (
tag?.match(/<[a-z]>/g)?.map(function (t, index) {
const text = tag.replace(/<[^>]+>/g, '');
return (
mappings.get?.(t.replace(/<|>/g, ''))?.(text, index) ?? null
);
})
);
})}
</Text>
);
});

用法

  <MiniMarkupText
text="<p>This is a simple</p> <b>test</b> <p>and it could be useful</p> <b>. Then again it all depends...</b>"
itemStyle=\{\{ color: 'red',  textAlign: 'center'}}
/>