[英]how to pass style using dangerouslySetInnerHTML in React
I'm injecting html in my react component using dangerouslySetInnerHTML in a format like this :我正在使用危险的SetInnerHTML 以如下格式在我的反应组件中注入html:
<div
className="mt-2 col variant-attr-cell p-0"
dangerouslySetInnerHTML = { {
__html: JSON.parse(attrs[i].snippet).snippet.replace("{text}",
attrs[i].choices[j].visualization_data)
} }
>
</div>
and it works fine but I'm trying to pass style to the injected html at the same time but don't know how!它工作正常,但我试图同时将样式传递给注入的 html 但不知道如何! I'm trying to add different styles to the injected html based on the api I get, something like this:
我正在尝试根据我得到的 api 向注入的 html 添加不同的样式,如下所示:
height: 12px;
width: 12px;
border-radius: 50%;
display: inline-block;
margin: 0 4px;
FYI the injected html is something like this mostly:仅供参考,注入的html主要是这样的:
<span></span>
and the styles must be added to this and not the container div!并且样式必须添加到此而不是容器 div! Any solution is appreciated, thanks.
任何解决方案表示赞赏,谢谢。
You can still add the desired style.您仍然可以添加所需的样式。 Just add another props
style
:只需添加另一个道具
style
:
const styleObj = {
color: 'white',
backgroundColor: 'red'
};
<div
className="mt-2 col variant-attr-cell p-0"
dangerouslySetInnerHTML = {
{ __html: JSON.parse(attrs[i].snippet).snippet
.replace("{text}", attrs[i].choices[j].visualization_data)
}
}
style={styleObj}
>
</div>
If you're trying to add style inside the element that resides in the html, then you should have their styles there in the html itself.如果您尝试在 html 中的元素内添加样式,那么您应该在 html 本身中包含它们的样式。
由于我从 API 获取 HTML,因此我在数据库中将 HTML 的样式属性设置为静态值,并在我的组件中替换了来自 API 的静态值!
I managed to do this by adding a ref to the container and using the useLayoutEffect hook.我设法通过向容器添加 ref 并使用 useLayoutEffect 钩子来做到这一点。
const elRef = useRef();
useLayoutEffect(()=>{
if (elRef.current){
elRef.current.firstElementChild.style.height = '12px';
// set other style attributes
...
}
});
return <div
ref={elRef}
dangerouslySetInnerHTML={yourHTML}
/>
This assumes you only want to style the first child of your container, but you could use a similar approach for multiple children.这假设您只想为容器的第一个子项设置样式,但您可以对多个子项使用类似的方法。
您可以像这样轻松地在危险HTML中设置元素样式 style='background-color:red' 而不是 style={{backgroundColor:'red'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.