乐闻世界logo
搜索文章和话题

Why styles don't apply on dangerouslySetInnerHTML using reactjs

1个答案

1

dangerouslySetInnerHTML is a React property used to directly insert HTML strings into components. Using this property bypasses React's virtual DOM to directly insert unescaped HTML into the real DOM, which introduces potential risks of cross-site scripting (XSS) attacks. Therefore, use it with caution to ensure content is safe. This is why the name includes 'dangerously'.

Regarding your question, why can't dangerouslySetInnerHTML be used to set styles, this is primarily because of its purpose and how it works. This property accepts an object where the __html key contains a string representing the HTML to insert. It directly targets the internal HTML of the element, rather than for handling styles.

If you want to indirectly set styles using dangerouslySetInnerHTML, you can include inline style HTML tags, such as:

jsx
function MyComponent() { return ( <div dangerouslySetInnerHTML={{ __html: '<style>.myClass { color: red; }</style><div class="myClass">Hello World</div>' }} /> ); }

In this example, we insert a <style> tag via dangerouslySetInnerHTML to define styles and then use them. However, this approach is not recommended because it may cause style pollution, affect styles in other parts, and be difficult to maintain and debug.

Typically, if you need to set styles, use React's built-in style attribute or define styles by importing CSS files. These methods are more secure and easier to manage and maintain. For example:

jsx
function MyComponent() { return ( <div style={{ color: 'red' }}> Hello World </div> ); }

Or, using CSS classes:

css
/* styles.css */ .myClass { color: red; }
jsx
import './styles.css'; function MyComponent() { return ( <div className="myClass"> Hello World </div> ); }

These methods are the standard and recommended ways to change the styles of React components.

2024年6月29日 12:07 回复

你的答案