我有很多这种格式的字符串:
'The model of that car is [assignment: any car model] and it has [assignment: any number] horsepower'
我想在我的 UI 中显示此字符串,并将每次出现的 [custom: text] 替换为文本框。我的
CustomComponent
实现了一个带有占位符的文本框。我希望占位符是“[custom:”和右方括号之间的文本。
我正在使用 reactStringReplace 来用 React 组件替换字符串模式。主要问题是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 = /\[assignment: (.*?)\]/g;
const regex_assignment = /\[assignment: (.*?)\]/;
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
的返回值是一个数组,而不是一个字符串(为了完成它的工作,它必须是一个字符串)。但你把它当作一个字符串。
您不需要在代码中包含循环,这是
reactStringReplace
为您做的事情之一,如“更现实的示例”部分所示。所以它更简单(我将正则表达式更改为使用 custom
而不是 assignment
,因为这就是 description
字符串中的内容):
function formatString(input) {
return reactStringReplace(input, /\[custom: (.*?)\]/g, (match, i) => (
<CustomComponent key={i} placeholder={match} />
));
}
(这是使用
key
的索引,这通常是一种反模式,但我认为选择正确的键超出了问题的范围。)
实例:
const reactStringReplace = module.exports;
function formatString(input) {
return reactStringReplace(input, /\[custom: (.*?)\]/g, (match, i) => (
<CustomComponent key={i} placeholder={match} />
));
}
// Stand-in for CustomComponent
function CustomComponent({ placeholder }) {
return <span className="placeholder">{placeholder}</span>;
}
function Example() {
const description =
"The model of that car is [custom: any car model] and it has [custom: any number] horsepower";
return (
<div className="description">
<div>{formatString(description)}</div>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Example />);
.placeholder {
color: blue;
font-weight: bold;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
<script>
const module = {};
</script>
<script src="https://unpkg.com/[email protected]/index.js"></script>