如何在React Native Text组件中动态加粗JSON字符串指定内容
React Native: Bold Specific Text in a String
To make "Self-Employed" bold while keeping the rest of the text's original styling, you can split the string into segments and nest <Text> components with targeted styles. Here are two practical solutions:
Approach 1: Manual Segmentation (Simple & Direct)
Split the dynamic string into three parts: the text before the bold term, the term itself, and the text after. Wrap each segment in <Text> components, applying bold styling only to the target term.
<Text style={{ fontSize: 16, lineHeight: 24, letterSpacing: 0.7, paddingRight: 20, fontWeight: "400" }}> {data3.split("Self-Employed")[0]} <Text style={{ fontWeight: "700" }}>Self-Employed</Text> {data3.split("Self-Employed")[1]} </Text>
Approach 2: Dynamic Splitting with Regex (Flexible for Multiple Occurrences)
Use a regular expression to split the string around the target term, then map over the resulting segments to apply bold styling conditionally. This works even if the term appears multiple times in the string.
const boldKeyword = "Self-Employed"; const textSegments = data3.split(new RegExp(`(${boldKeyword})`, "gi")); return ( <Text style={{ fontSize: 16, lineHeight: 24, letterSpacing: 0.7, paddingRight: 20, fontWeight: "400" }}> {textSegments.map((segment, index) => ( <Text key={index} style={{ fontWeight: segment === boldKeyword ? "700" : "400" }} > {segment} </Text> ))} </Text> );
内容的提问来源于stack exchange,提问作者WaqasArshad
相关产品推荐
相关产品推荐

