简体   繁体   中英

how to pass style using dangerouslySetInnerHTML in React

I'm injecting html in my react component using dangerouslySetInnerHTML in a format like this :

<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! I'm trying to add different styles to the injected html based on the api I get, something like this:

height: 12px;
width: 12px;
border-radius: 50%;
display: inline-block;
margin: 0 4px;

FYI the injected html is something like this mostly:

<span></span>

and the styles must be added to this and not the container div! Any solution is appreciated, thanks.

You can still add the desired style. Just add another props 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.

由于我从 API 获取 HTML,因此我在数据库中将 HTML 的样式属性设置为静态值,并在我的组件中替换了来自 API 的静态值!

I managed to do this by adding a ref to the container and using the useLayoutEffect hook.

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'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM