简体   繁体   English

在 React 中为字符串的特定单词加下划线

[英]Underline specific words of a string in React

So I've got a string being sent to a class that is split by \n for format.所以我有一个字符串被发送到 class 被 \n 分割的格式。 I was wondering if it was possible to underline specific words of the string so it looks better?我想知道是否可以在字符串的特定单词下划线以使其看起来更好?

Currently this is what is being passed目前这是正在通过的

"Name : Jackson 
\nLabel: Movie
\nDirector: 
\nGenre: Action
\nActors: Will, Jack, Carrie
\nMetascore: 90/100
\nRevenue: 87.5M
\nRuntime: 100 min
\nRating: 9/10"

And I would like for the word after the \n until the ":" to be underlined but all I've seen are making an entire string underlined.我希望在 \n 之后的单词直到 ":" 加下划线,但我所看到的只是将整个字符串加下划线。

Heres how I'm currently parsing the string.以下是我当前解析字符串的方式。

 const newText = text.split('\n').map(str => <p>{str}</p>);

My guess would be to have str split again by: inside the.map and using <Text style={styles.bold}> </Text> to set it?我的猜测是让 str 再次拆分:在.map 内部并使用<Text style={styles.bold}> </Text>进行设置?

You can split each line of your text by : , like below:您可以通过:分割文本的每一行,如下所示:

const string = `
Name: Jackson 
Label: Movie
Director: 
Genre: Action
Actors: Will, Jack, Carrie
Metascore: 90/100
Revenue: 87.5M
Runtime: 100 min
Rating: 9/10
`;

function MyList() {
  const strings = string.split('\n').map((str) => {
    const [label, value] = str.split(':');
    return (
      <div>
        <u>{label}</u>:<p>{value}</p>
      </div>
    );
  });

  return strings;
}

<u> stands for underline in html. <u>代表 html 中的下划线。

You can also add a className attribute to the tag surrounding the label part and use text-decoration: underline;您还可以将className属性添加到围绕label部分的标记并使用text-decoration: underline;

Try text.split(/[\n:]/) .尝试text.split(/[\n:]/)
After that - put each uneven element into a tag.之后 - 将每个不均匀的元素放入标签中。
Of course it will work only if there are no other colons or new lines in text.当然,只有在文本中没有其他冒号或换行时它才会起作用。

 const str = "Name: Jackson\nLabel: Movie\nDirector: \nGenre: Action\nActors: Will, Jack, Carrie\nMetascore: 90/100\nRevenue: 87.5M\nRuntime: 100 min\nRating: 9/10" console.log(str.split(/\s?[\n:]\s?/).map((s, i) => i % 2 === 0? ('<u>' + s + '</u>:'): (' ' + s + '\n')).join(''))

Split the string inside the map function, wrap it in span tags and use text-decoration: underline;拆分 map function 内的字符串,将其包裹在 span 标签中并使用text-decoration: underline; for css.对于 css。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM