[英]React add HTML tags on string using predetermined components (alternative to dangerouslySetInnerHTML )
I do not want to employ dangerouslySetInnerHTML and the objective here is to put bold tags around each instance of a word that appears in my string.我不想使用危险的SetInnerHTML,这里的目标是在我的字符串中出现的每个单词实例周围放置粗体标记。
Convention React wisdom might suggest that something like this could work?约定 React 智慧可能表明这样的事情可以工作?
const Bold = (props) => {
return (
<b>
{props.txt}
</b>
);
};
Here is where I try to incorporate the code这是我尝试合并代码的地方
if (longString.includes(searchTerm)) {
longString = longString.replace(rest, <Bold txt={rest} />);
}
Problem is it comes out as [object Object] instead of desired <b>searchTerm</b>问题是它作为[object Object]而不是所需的<b>searchTerm</b>
How do I do set up the string swap so that it doesn't print the word [object] but rather prints the object?如何设置字符串交换,使其不打印单词 [object] 而是打印对象?
You could try renderToString
from react-dom
你可以从react-dom
尝试renderToString
import { renderToString } from 'react-dom/server'
if (longString.includes(searchTerm)) {
longString = longString.replace(rest, renderToString(<Bold txt={rest} />) );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.