Reactjs react字符串替换不使用正则表达式

Reactjs react字符串替换不使用正则表达式,reactjs,string,replace,Reactjs,String,Replace,我试图使用库react string replace,因为在react中,我们使用string replace方法的方法有限 我曾使用regex尝试匹配一些子字符串,如下所述,如文档中所示,但我无法获得所需的结果。我做错什么了吗 const str = 'Hey this a sample string.' const result = reactStringReplace(str, '/(sample)/g', match => <span style={{fontStyle: '

我试图使用库react string replace,因为在react中,我们使用string replace方法的方法有限

我曾使用regex尝试匹配一些子字符串,如下所述,如文档中所示,但我无法获得所需的结果。我做错什么了吗

const str = 'Hey this a sample string.'
const result = reactStringReplace(str, '/(sample)/g', match => <span style={{fontStyle: 'italic'}}>{match}</span>)
const str='Hey this a sample string'
const result=reactStringReplace(str,'/(sample)/g',match=>{match})
上述代码不会更改字符串的样式。但是当我删除正则表达式并放置一个简单的字符串时,它就工作了

const str = 'Hey this a sample string.'
const result = reactStringReplace(str, 'sample', match => <span style={{fontStyle: 'italic'}}>{match}</span>)
const str='Hey this a sample string'
const result=reactStringReplace(str'sample',match=>{match})

我想使用正则表达式来实现这一点,因为还有两个其他字符串我想应用相同的样式。提前谢谢。

我不明白你为什么需要一个特殊的软件包来完成这项工作,不是吗

const str = 'Hey this a sample string.'
const patt = /(sample)/g
match = str.match(new RegExp(patt))

return <span style={{fontStyle: 'italic'}}>{match}</span>
const str='Hey this a sample string'
常量参数=/(样本)/g
match=str.match(新RegExp(patt))
返回{match}

您需要从示例正则表达式中删除单引号
'

编辑:您需要在返回的JSX中添加一个
道具,否则您将在日志中得到一个
警告
:列表中的每个子项都应该有一个唯一的“键”道具

语法应该如下所示:

const str='Hey this a sample string'
const result=reactStringReplace(str,/(sample)/g,(match,i)=>{match})


实际上,您不需要一个库来完成这项工作,您可以使用React方法来完成

函数应用程序(){
const[text,setText]=React.useState(“”)
常量handleClick=()=>{
const str=“这是一个示例字符串。”
//您需要使用常规内联CSS
const result=str.replace(
“样本”,
“样本”
)
setText(结果)
}
返回(
更改文本样式

) } ReactDOM.render(,document.getElementById('root'))