ReactJS:reactStringReplace替换字符串模式为自定义组件的异常问题
问题
我有如下格式的字符串:
'The model of that car is [custom: any car model] and it has [custom: any number] horsepower'
需要在UI中展示该字符串,并把每一处[custom: text]替换为带占位符的文本框(我的CustomComponent支持占位符,占位符取[custom:和]之间的文本)。
使用reactStringReplace做替换时遇到问题:所有替换后的组件都用了同一个占位符。即使去掉正则末尾的/g只匹配单次,所有匹配项还是会被替换,且占位符完全相同。
错误代码示例
const reactStringReplace = require('react-string-replace'); const description = 'The model of that car is [custom: any car model] and it has [custom: any number] horsepower' function formatString(input){ const regex = /\[custom: (.*?)\]/g; const regex_assignment = /\[custom: (.*?)\]/; let formattedString = input; let match; let placeholder; let newString = input; while ((match = regex.exec(input)) !== null) { placeholder = match[1]; newString = reactStringReplace(newString,regex_assignment, ()=> (<CustomComponent placeholder={placeholder}/>)) } return(newString); } return ( <div class = 'description'> <div>{formatString(description)}</div> </div> );
问题原因
你的循环逻辑存在两个问题:
reactStringReplace默认会全局匹配替换所有符合正则的内容,哪怕传入的正则不带/g,因此每次循环都会把所有[custom: ...]替换一遍。- 循环中每次更新
placeholder后,所有替换回调都会引用当前的placeholder变量,最终所有组件都会拿到最后一次循环的占位符值。
正确解决方案
reactStringReplace本身支持在回调中获取正则捕获的分组内容,不需要手动写循环。一次调用就能完成所有替换,且每个组件能拿到对应的占位符:
const reactStringReplace = require('react-string-replace'); const description = 'The model of that car is [custom: any car model] and it has [custom: any number] horsepower' function formatString(input) { // 直接使用带/g的正则,reactStringReplace会自动遍历所有匹配项 return reactStringReplace(input, /\[custom: (.*?)\]/g, (fullMatch, placeholderText) => { // placeholderText就是正则捕获的占位符内容 return <CustomComponent placeholder={placeholderText} />; }); } return ( <div className='description'> <div>{formatString(description)}</div> </div> );
关键说明
reactStringReplace的回调函数会接收多个参数:第一个是完整匹配的字符串,后面依次是正则中捕获分组的内容,这里直接用第二个参数作为占位符即可。- 无需手动循环,该方法会自动处理所有全局匹配项,每个匹配项都会独立调用回调生成组件,不会出现占位符复用的问题。
- 注意将
class改为className,React中元素的类名属性需用className,避免DOM属性警告。
内容的提问来源于stack exchange,提问作者Rodolfo
相关产品推荐
相关产品推荐

