如何使用replace在React中为字符串的特定部分添加颜色? [英] How to add color to a specific part of a string in React using replace?

查看:779
本文介绍了如何使用replace在React中为字符串的特定部分添加颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符串中的所有数字设为红色,然后使用React进行渲染. 这就是我想要做的(我已经使用create-react-app制作了一个应用,并用我自己的内容替换了App.js的内容):

I'd like to make all the numbers in a string red and then render it with React. Here's what I'm trying to do (I've made an app using create-react-app and replaced the contents of App.js with my own):

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  render() {
    const str = 'foo123bar';

    const strColor = 
      str.replace(/\d+/, match => <span style={{color: 'red'}}> {match} </span> );

    return (
      <div className="App">
        {strColor}
      </div>
    );
  }
}

export default App;

结果是仅在视口中渲染了线foo[object Object]bar.

As a result only the line foo[object Object]bar was rendered in the viewport.

那么应该如何将内联样式添加到JSX?

So how should inline styling be added to JSX?

推荐答案

那么应该如何将内联样式添加到JSX?"

"So how should inline styling be added to JSX?"

要回答您提出的问题,请输入以下行:

To answer to your stated question, your line:

const strColor = str.replace(/\d+/, match => <span style={{color: 'red'}}> {match} </span> );

返回一个字符串-所以对象语句style={{color: 'red'}}> 不会逃脱.

is returning a string - so the object statement style={{color: 'red'}}> will not be escaped.

添加带有字符串定义的内联样式,引用双引号并删除花括号:
<span style="color: red"> {match} </span>

Add the inline styling with a string definition instead, reference the double quotes and removed curly braces:
<span style="color: red"> {match} </span>

您可以通过以下分隔符来添加更多样式:用逗号分隔值:值对:
<span style="color: red, text-decoration: underline"> {match} </span>

You can add more styles by separating the key: value pairs with commas:
<span style="color: red, text-decoration: underline"> {match} </span>


请注意,这将不起作用
您真正要回答的问题是如何用组件替换字符串的一部分(在本例中为带有样式的<span>标签.此问题记录在react github issue页面中,请注意,有很多问题选项,而无需按照前面的几个答案中所述危险地设置内部HTML: https://github .com/facebook/react/issues/3386


Note that this will not work
The question that you're really trying to answer is how to replace parts of a string, with a component (in this case a <span> tag with styling. This issue is documented in the react github issues page, note that there are many options without requiring you to dangerously set your inner HTML as noted in several previous answers: https://github.com/facebook/react/issues/3386

这篇关于如何使用replace在React中为字符串的特定部分添加颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆