我有业务,我正在尝试返回业务数组,我正在为此使用 map 概念,我正在尝试在索引 == 3 时添加新部分,我也正在尝试在不添加父 div 的情况下获得此结果.请检查我的代码js fiddle demo
const business = [
"business1",
"business2",
"business3",
"business4",
"business5"
]
class Hello extends React.Component {
render() {
return (
<div>
{
business.map((data,index) => {
return index===3 ? <div>New Section</div><div>{data}</div>:<div>{data}</div>
})
}
</div>
)
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
如果我添加 parent parent div 我可以获得结果但是我想在索引 === 3 时不添加 parent div 来获得结果,因为在添加 parent 时我无法实现我的设计输出 预期输出
business1
business2
business3
newsection
business4
business5
最佳答案
从 React 16.2 开始,您可以使用片段。在 JSX 中,您可以简单地将元素包装在看起来像一个空名称的元素中:
<>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</>
~ 来自 https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html 的示例.
如果您使用 Babel 来转译代码,您可能需要使用 <React.Fragment></React.Fragment>
而不是 <></>
.
关于javascript - 如何解决相邻的 JSX 元素必须包裹在 React 中的封闭标签问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47781431/