如何在react片段中添加条件语句



在react片段内部,我必须添加条件语句。根据条件语句,返回预期的

return (
<React.Fragment>
<Toolbar
pageTitle={i18next.t('TITLE')}
iconButtons={this.state.icons}
{this.props.abc && this.props.abc.operation ?(
moreButton={moreButton}
):null}
/>

如果this.props.abc.operation存在,那么只显示更多按钮如果不只显示iconbuttons这是我的条件,上面是我尝试的代码。任何帮助都将不胜感激。

<>
<Toolbar
pageTitle={i18next.t('TITLE')}
iconButtons={this.state.icons}
moreButton={this.props.abc && this.props.abc.operation && moreButton}
/>
</>

试着使用这个。

您可以执行以下操作,而不是条件渲染。

isAbcOperationExist = (args) => {
if(args && args.operation){
return true;
}
return false;
}

现在内部组件道具:

<Toolbar
pageTitle={i18next.t('TITLE')}
iconButtons={this.state.icons}
showMoreButton={() => this.isAbcOperationExist(this.props.abc)}
/>

根据方法isAbcOperationExist返回的布尔值结果,您可以显示或隐藏更多按钮

更多示例:

假设这是基于类的组件:

class YourComponent extends React.Component {
constructor(props){
super(props)  
}
isAbcOperationExist = (args) => {
if(args && args.operation) {
return true;
}
return false;
}

render (){
return (
<Toolbar
pageTitle={i18next.t('TITLE')}
iconButtons={this.state.icons}
moreButton={moreButton}
showMoreButton={() => this.isAbcOperationExist(this.props.abc)}
/>
)
}
}

对于工具栏组件,假设其为功能基础组件:

const Toolbar = ({pageTitle, iconButtons, showMoreButton, moreButton}) => {
return(
<div>
{
showMoreButton ? <button onClick={moreButton}>Show More</button> : null
}
</div>
)
}

React Fragment与此无关。你也不能像这样操纵组件道具。这个想法是为iconButtons和moreButton提供一个单独的道具,并执行在工具栏组件中显示的逻辑

最新更新