[英]What is the React equivelant of Angulars 'ng-container'
Instead of having a div element, I want an element like 'ng-container' in Angular to avoid useless div elements in the DOM.我想要一个像 Angular 中的“ng-container”这样的元素,而不是一个 div 元素,以避免在 DOM 中出现无用的 div 元素。
What is the React equivalent of Angulars 'ng-container' ? Angulars 'ng-container' 的 React 等价物是什么?
You can use React.Fragment
您可以使用
React.Fragment
<React.Fragment>
"Rest of elements here"
</React.Fragment>
Fragments let you group a list of children without adding extra nodes to the DOM. 片段允许您将子列表分组,而无需向DOM添加额外节点。
function ChildA() {
return (
<h5>Child A</h5>
);
}
function ChildB() {
return (
<h5>Child B</h5>
);
}
function ChildC() {
return (
<h5>Child C</h5>
);
}
Method-1: React Fragments helps to add empty container to wrap list of children inside render method. 方法-1: React Fragments有助于添加空容器以包装render方法中的子列表。
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
Method-2 A common pattern is for a component to return a list of children by wrapping children with any container element eg div,p 方法-2一个常见的模式是组件通过使用任何容器元素( 例如div,p)包装子项来返回子项列表
render() {
return (
<div>
<ChildA />
<ChildB />
<ChildC />
</div>
);
}
Method-3 There is a new, shorter syntax you can use for declaring fragments.You can use <> the same way you'd use any other element except that it doesn't support keys or attributes. 方法-3您可以使用一种新的,更短的语法来声明片段。您可以使用<>,就像使用任何其他元素一样,除了它不支持键或属性。
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
Method-4 React 16.0 added support for returning an array of elements from a component's render method. 方法-4 React 16.0增加了对从组件的render方法返回元素数组的支持。 Instead of wrapping the children in a DOM element, you can put them into an array:
您可以将它们放入数组中,而不是将子项包装在DOM元素中:
function App() {
return (
[
<ChildA />,
<ChildB />,
<ChildC />
]
);
}
We can use empty <>
tag as well我们也可以使用空的
<>
标签
<>
Rest of markup here
</>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.