React.js: Set innerHTML vs dangerouslySetInnerHTML

后端 未结 4 1148
死守一世寂寞
死守一世寂寞 2020-11-29 15:42

Is there any \"behind the scenes\" difference from setting an element\'s innerHTML vs setting the dangerouslySetInnerHTML property on an element? Assume I\'m properly saniti

4条回答
  •  有刺的猬
    2020-11-29 16:38

    According to Dangerously Set innerHTML,

    Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.

    Our design philosophy is that it should be "easy" to make things safe, and developers should explicitly state their intent when performing “unsafe” operations. The prop name dangerouslySetInnerHTML is intentionally chosen to be frightening, and the prop value (an object instead of a string) can be used to indicate sanitized data.

    After fully understanding the security ramifications and properly sanitizing the data, create a new object containing only the key __html and your sanitized data as the value. Here is an example using the JSX syntax:

    function createMarkup() {
        return {
           __html: 'First · Second'    };
     }; 
    
    

    Read more about it using below link:

    documentation: React DOM Elements - dangerouslySetInnerHTML.

提交回复
热议问题