问题描述
我是React的新手,我正试图找出< MyComponent>< / MyComponent>的目的/用途vs< MyComponent />。我似乎无法找到除自动关闭标签之外的任何信息。
I'm new to React and I'm trying to figure out the purpose/use of <MyComponent></MyComponent> vs <MyComponent />. I can't seem to find information on anything except self-closing tags.
我已经创建了一个基本的标签卷轴作为使用自闭合< MyComponent />以及随后的道具,我想知道在React中写一个比我做的更好的方法。
I've created a basic tab scroller as a JSFiddle using the self-closing <MyComponent /> and subsequent props, and I'm wondering if there's a better way to write in React than what I've done.
class TabScroller extends React.Component {
render() {
return (
<div className="tabScroller">
<div className="NavList">
<TabNav handleClick={this.handleNavClick} />
<TabList
tabs={this.state.tabs}
activeTab={this.state.activeTab}
scrollPosition={this.state.scrollPosition}
handleClick={this.handleTabClick}
/>
</div>
<TabContent content={this.state.tabs[this.state.activeTab].content} />
</div>
);
}
}
// ========================================
ReactDOM.render(
<TabScroller />,
document.getElementById('root')
);
推荐答案
在React的JSX中,你只需要写< MyComponent>< / MyComponent>
当组件包含子组件时,如下所示:
In React's JSX, you only need to write <MyComponent></MyComponent>
when the component has child components, like this:
<MyComponent>
<Child />
<Child />
<Child />
</MyComponent>
如果< MyComponent>
和< / MyComponent>
,然后你可以把它写成< MyComponent />
或< MyComponent>< / MyComponent>
(但通常首选< 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.
作为附注,您可以通过特殊的 props.children
属性访问组件中的子项。更多内容见。
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.
请注意,这非常像HTML或XHTML一样不。它是自己的(类似的)具有不同规则的东西。例如,在HTML中,< div />
与< div>
完全相同:A start 标记,您最终必须拥有结束标记。不是这样的JSX(或XHTML)。 HTML的规则是 void elements (从不具有标记内容的元素,例如 br
或 img
)可以在>
之前使用或不使用 /
编写,但他们永远不会得到结束标记,但是非void元素(如 div
)必须始终有一个结束标记(< / div>
),它们不能自我关闭。在JSX(和XHTML)中,它们可以是。
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.
这篇关于React组件结束标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!