gpt4 book ai didi

javascript - 多个元素的条件渲染

转载 作者:行者123 更新时间:2023-12-05 01:58:16 26 4
gpt4 key购买 nike

如果当前用户是创建我目前所在的组的用户,我想渲染 3 个额外的按钮,所以我尝试了这样的操作:

render(){
let adminButtons;
if (this.state.groupData && this.props.user.id){
if(this.state.groupData.owner === this.props.user.id){
adminButtons = {
<CustomButton>Add Quiz</CustomButton>
<CustomButton>Drafts</CustomButton>
<CustomButton>Delete Group</CustomButton> };
}
else{
adminButtons = <div/>;
}
}
}
return(
<div className='group-page'>
<div className='group-controls'>

<div className='admin-buttons'>
{adminButtons}
</div>
</div>

</div>
)}

但此实现会引发编译器错误,我该如何更改代码才能使其正常工作? JSX 表达式必须有一个父元素,这是我得到的错误

最佳答案

简短的回答是您可以将组件包装在 React.Fragment 中.

 <>
<CustomButton>Add Quiz</CustomButton>
<CustomButton>Drafts</CustomButton>
<CustomButton>Delete Group</CustomButton>
</>

根据文档:

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

关于javascript - 多个元素的条件渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68640091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com