React component closing tag

后端 未结 2 1333
无人共我
无人共我 2020-12-10 12:25

I\'m new to React and I\'m trying to figure out the purpose/use of vs . I can\'t seem to find information on any

相关标签:
2条回答
  • 2020-12-10 12:49

    The purpose of self-closing tags is simply the fact that it is more compact. This is especially useful when said component doesn't have any children that you typically wrap around a parent.

    So usually for leaf components (i.e compoents that do not have any children), you use the self-closing syntax. Like: <Component />. And even if it has props, you can do: <Component foo="bar" />.

    However, remember that children is a prop, so you could technically do:

    <Component children={<span>foo</span>} />

    but I find it less readable and advise against it (read disclaimer below).


    To summarize, these are equivalent:

    • <Component /> = <Component></Component>
    • <Component foo="bar" /> = <Component foo="bar"></Component>
    • <Component children={<span>foo</span>}></Component> =

      <Component><span>foo</span></Component>

    You can use whichever approach you prefer. Though praxis is to use the short-hand version when there are no children.


    Disclaimer: While defining childen prop by its object key value will technically work, doing so is strongly discouraged as it disrupts the API as it is meant to be used. Use this version only if confident in what you are doing.

    0 讨论(0)
  • 2020-12-10 12:58

    In React's JSX, you only need to write <MyComponent></MyComponent> when the component has child components, like this:

    <MyComponent>
        <Child />
        <Child />
        <Child />
    </MyComponent>
    

    If there is nothing between <MyComponent> and </MyComponent>, then you can write it either <MyComponent/> or <MyComponent></MyComponent> (but <MyComponent/> is generally preferred). Details in Introducing JSX.

    Just as a side note, you'd access those children in your component via the special props.children property. More in JSX in Depth: Children in JSX.

    Note that this is very much not like HTML or XHTML. It's its own (similar) thing with different rules. For instance, in HTML, <div/> is exactly the same thing as <div>: A start tag, for which you must eventually have an end tag. Not so JSX (or XHTML). The rules for HTML are that void elements (elements that never have markup content, such as br or img) can be written with or without / before > and they never get an ending tag, but non-void elements (like div) must always have an ending tag (</div>), they cannot be self-closing. In JSX (and XHTML), they can be.

    0 讨论(0)
提交回复
热议问题