如何在React Fragment内添加条件语句并实现Toolbar组件条件传参
React组件条件传递属性的正确写法
你的代码问题在于JSX的属性语法不支持直接在属性列表里嵌入三元表达式输出键值对,这种写法会被识别为无效语法。下面给你两种可行的解决方式:
方法一:使用条件扩展运算符(推荐)
利用ES6的扩展运算符,结合可选链判断属性是否存在,简洁直观:
return ( <React.Fragment> <Toolbar pageTitle={i18next.t('TITLE')} iconButtons={this.state.icons} {/* 当abc.operation存在时,扩展传入moreButton属性 */} {...(this.props.abc?.operation && { moreButton })} /> </React.Fragment> );
这里的?.是可选链操作符,能避免this.props.abc不存在时触发报错,比原代码的this.props.abc && this.props.abc.operation更安全。
方法二:提前构建属性对象
如果需要更复杂的逻辑,可以先定义属性对象,再根据条件添加属性:
return ( <React.Fragment> {(() => { const toolbarProps = { pageTitle: i18next.t('TITLE'), iconButtons: this.state.icons }; // 条件满足时添加属性 if (this.props.abc?.operation) { toolbarProps.moreButton = moreButton; } return <Toolbar {...toolbarProps} />; })()} </React.Fragment> );
内容的提问来源于stack exchange,提问作者jaanaki
相关产品推荐
相关产品推荐

