How to add color to a specific part of a string in React using replace?

一世执手 提交于 2021-01-28 04:22:20

问题


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;

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

So how should inline styling be added to JSX?


回答1:


"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> );

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

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

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


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




回答2:


I was able to solve this by using 'dangerouslySetInnerHTML'.

class App extends React.Component {
  render() {
      let str = 'foo123bar';

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

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

} }




回答3:


You can't insert HTML into a string for it to be rendered in React, this exists as a protection from XSS.

What you can do in a case like this is something like:

const str = 'foo123bar';

const coloredStr = str.match(/\d+/);
const [before, after] = str.split(/\d+/)

return (
  <div className="App">
    {before}
    {coloredStr && coloredStr[0] && 
       <span style="color: red">{coloredStr[0]}</span>
    }
    {after}
  </div>
);

For a more complex example you will need more complex logic. E.g. multiple parts can be styled - you can find all the matches and the non matching parts and put them in a list in the right order with an indicator should you use the span or not. Something like:

list.map((elem) => elem.isColored ? <span style="color: red">{elem.value}</span> : elem.value)

EDIT

As mentioned in the comments, here is an implementation for multiple elements:

const str = 'foo123bar456baz897ban';
let strCopy = str;
const list = [];

while(strCopy) {
    const text = strCopy.split(/\d+/, 1)[0];
    list.push(text);
    const match = strCopy.match(/\d+/);
    if (!match) {
        break;
    }
    list.push(match[0]);
    strCopy = strCopy.substring(match.index + match[0].length);
}

return (
  <div className="App">
    {list.map((elem, index) => index % 2 === 0
         ? elem
         : <span style="color: red">{elem}</span>
    )}
  </div>
);


来源:https://stackoverflow.com/questions/54562124/how-to-add-color-to-a-specific-part-of-a-string-in-react-using-replace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!