我需要在dangerouslySetInnerHTML中插入一个变量。
import serviceAPI from "serviceAPI";
const [content,setContent] = useState("");
const [firstName,setFirstName] = useState("Thomas");
useEffect(() => {
fetchContent()
}, [])
const fetchContent = async () => {
// Return string : "<h1>Hello {firstName}</h1>"
const result = await serviceAPI.getContent()
setContent(text)
}
return (
<p dangerouslySetInnerHTML={{ __html: content.toString() }}></p>
)
此代码的结果:Hello {firstName}
我需要的结果是:Hello Thomas
发布于 2020-10-05 07:38:39
您可以使用字符串内插或简单连接将变量插入到字符串中:
const text = `<h1>Hello ${firstName}</h1>`此外,您还需要将firstName添加到useEffect的依赖项列表中。
在您的代码示例中,您不需要使用useEffect,我会将其更改为:
const [firstName,setFirstName] = useState("Thomas")
const content = `<h1>Hello ${firstName}</h1>`
return (
<p dangerouslySetInnerHTML={{ __html: content }} />
)如果从API返回字符串,则可以使用regex搜索并替换:
const text = "<h1>Hello {firstName}</h1>"
const newText = text.replace(/{firstName}/g, firstName)https://stackoverflow.com/questions/64204240
复制相似问题