React hooks:setState()与包含html的字符串



我正在尝试从包含html的json文件值中设置State。所以类似于:

...
const quote = [quote, setQuote] = useState('');
const quotes = [
{ quote: "Some text." },
{ quote: 'Some text with <span class="red">HTML</span>.' },
];
const handleClick = () => {
setQuote(quotes[1].quote);
};
...
return (
<div>{quote}</div> // right now it's printing the html as text.
);

使用dangeriousySetInnerHTML解析和呈现HTML字符串。您可能还想使用DOMPurify清除/净化任何值。

示例:

import DOMPurify from "dompurify";
...
const quote = [quote, setQuote] = useState('');
const quotes = [
{ quote: "Some text." },
{ quote: 'Some text with <span class="red">HTML</span>.' },
];
const handleClick = () => {
setQuote(quotes[1].quote);
};
...
return (
<div dangerouslySetInnerHTML ={{ __html: DOMPurify.sanitize(quote) }} />
);

使用dangerouslySetInnerHTML:插入原始HTML

return (
<div dangerouslySetInnerHTML={{__html: quote }}></div>
);

从文本中注入html总是有风险的,但我认为这应该有效:

import { useRef } from 'react';
...
const quoteRef = useRef(null);
const quotes = [
{ quote: "Some text." },
{ quote: 'Some text with <span class="red">HTML</span>.' },
];
const handleClick = () => {
if(!quoteRef.current) return; //Just in case the element got deleted
quoteRef.current.innerHTML = quotes[1].quote;
};
...
return (
<div ref={quoteRef}>{quote}</div> // right now it's printing the html as text.
);

最新更新