JSX三元运算符首个分支返回多元素问题求助
问题解决:JSX三元分支中同时渲染map结果与静态组件
你遇到的问题是JSX不允许相邻的兄弟元素没有父容器包裹——你的尝试里,map返回的组件数组和<ExtraComponent/>直接放在括号里,属于相邻元素,不符合JSX语法规则,所以无法正常渲染。
下面是几种可行的解决方法:
方法1:使用React.Fragment(推荐)
用Fragment包裹两个元素,不会额外生成多余的DOM节点,语法可以用简洁的短形式<>...</>:
{ this.state.loading ? <LoaderComponent/> : this.state.status ? ( <> {this.state.config.map((input, key) => { return this.getComponent(input, key) })} <ExtraComponent/> </> ) : '' }
如果你的React版本不支持短语法,可使用完整的<React.Fragment>标签:
{ this.state.loading ? <LoaderComponent/> : this.state.status ? ( <React.Fragment> {this.state.config.map((input, key) => { return this.getComponent(input, key) })} <ExtraComponent/> </React.Fragment> ) : '' }
方法2:用普通DOM容器包裹
如果不介意多生成一个DOM节点(比如<div>),可以直接用它包裹两个元素:
{ this.state.loading ? <LoaderComponent/> : this.state.status ? ( <div> {this.state.config.map((input, key) => { return this.getComponent(input, key) })} <ExtraComponent/> </div> ) : '' }
方法3:把静态组件合并到map数组中
如果想避免额外容器,也可以把<ExtraComponent/>追加到map返回的数组末尾:
{ this.state.loading ? <LoaderComponent/> : this.state.status ? this.state.config.map((input, key) => { return this.getComponent(input, key) }).concat(<ExtraComponent key="extra" />) : '' }
注意这里要给<ExtraComponent/>添加唯一的key属性,符合React列表渲染的规范要求。
内容的提问来源于stack exchange,提问作者Elichy
相关产品推荐
相关产品推荐

