dangerouslySetInnerHTML in React

        dangerouslySetInnerHTML, the translation is: dangerously set inner HTML.

        Why does it say dangerous settings? Be aware that there is such a saying: "Never trust user input". Sometimes the user does not input data according to the rules envisaged by the programmer. For example, if the user is expected to input numbers, the user enters text, and similar situations abound.

1. The role of dangerouslySetInnerHTML

        When the data entered or obtained by the user is a piece of HTML code, dangerouslySetInnerHTML can turn this piece of code into HTML, and then insert it somewhere, similar to innerHTML in JS .

        For example, we need to make a demo of todoList. When the user enters HTML code, if dangerouslySetInnerHTML is not set, then it will be a string of HTML code when displayed:

         result:

 Two, the syntax of dangerouslySetInnerHTML

        dangerouslySetInnerHTML appears as a tag attribute , and the value is an object. There is an attribute in the object, which is also an object:

         __html is a fixed way of writing, and the following item indicates the content to be inserted. If the inserted content is HTML code, it will be rendered in HTML and then displayed on the page; if the content to be inserted is other text, it will have no effect.

 3. Why is it a dangerous setting?

        Inserting HTML at an inappropriate time may cause the website to be attacked by XSS by some unscrupulous elements . The author named it dangerouslySetInnerHTML to warn programmers not to use this attribute at will.

 

Guess you like

Origin blog.csdn.net/txl2498459886/article/details/127213382