我想将字符串中的所有数字设置为红色,然后使用React进行渲染。这是我正在尝试做的事情(我使用create-react-app
创建了一个应用程序并用我自己的内容替换了App.js的内容):
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
线。
那么如何在JSX中添加内联样式?
“那么如何在JSX中添加内联样式?”
要回答您提出的问题,请说明您的问题:
const strColor = str.replace(/\d+/, match => <span style={{color: 'red'}}> {match} </span> );
返回一个字符串 - 所以对象语句style={{color: 'red'}}>
不会被转义。
使用字符串定义添加内联样式,引用双引号并删除花括号:
<span style="color: red"> {match} </span>
您可以通过用逗号分隔键:值对来添加更多样式:
<span style="color: red, text-decoration: underline"> {match} </span>
请注意,这不起作用
你真正想要回答的问题是如何用一个组件替换一个字符串的部分(在这种情况下是带有样式的<span>
标签。这个问题记录在react github问题页面中,注意有很多选项没有要求你危险地设置内部HTML,如前几个答案中所述:https://github.com/facebook/react/issues/3386
我能够通过使用'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>
);
} }
您不能将HTML插入字符串中以便在React中呈现,这是对XSS的保护。
在这样的情况下你可以做的是:
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>
);
对于更复杂的示例,您将需要更复杂的逻辑。例如。可以设置多个部分的样式 - 您可以找到所有匹配和不匹配的部分,如果您使用跨度,则可以使用指示符将它们按正确的顺序放入列表中。就像是:
list.map((elem) => elem.isColored ? <span style="color: red">{elem.value}</span> : elem.value)
编辑
正如评论中所提到的,这是一个多元素的实现:
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>
);