React - How to pass HTML tags in props?

前端 未结 20 1291
甜味超标
甜味超标 2020-12-07 11:58

I want to be able to pass text with HTML tags, like so:

not working.\" />

Bu

20条回答
  •  独厮守ぢ
    2020-12-07 12:28

    Actually, there are multiple ways to go with that.

    You want to use JSX inside your props

    You can simply use {} to cause JSX to parse the parameter. The only limitation is the same as for every JSX element: It must return only one root element.

    myProp={
    Some String
    }

    The best readable way to go for this is to create a function renderMyProp that will return JSX components (just like the standard render function) and then simply call myProp={ this.renderMyProp() }

    You want to pass only HTML as a string

    By default, JSX doesn't let you render raw HTML from string values. However, there is a way to make it do that:

    myProp="
    This is some html
    "

    Then in your component you can use it like that:

    Beware that this solution 'can' open on cross-site scripting forgeries attacks. Also beware that you can only render simple HTML, no JSX tag or component or other fancy things.

    The array way

    In react, you can pass an array of JSX elements. That means:

    myProp={["This is html", Some other, "and again some other"]}
    

    I wouldn't recommend this method because:

    • It will create a warning (missing keys)
    • It's not readable
    • It's not really the JSX way, it's more a hack than an intended design.

    The children way

    Adding it for the sake of completeness but in react, you can also get all children that are 'inside' your component.

    So if I take the following code:

    
        
    Some content
    Some content

    Then the two divs will be available as this.props.children in SomeComponent and can be rendered with the standard {} syntax.

    This solution is perfect when you have only one HTML content to pass to your Component (Imagine a Popin component that only takes the content of the Popin as children).

    However, if you have multiple contents, you can't use children (or you need at least to combine it with another solution here)

提交回复
热议问题