首页 > 解决方案 > 无法在反应中添加if语句

问题描述

嗨,我发现在 React 中添加 if 语句很困难。添加 if 语句时显示编译错误。下面是我的代码。

 {parametersSearchResults.length > 0 && [
            <ButtonWithMargin
              key="filter"
              label="Filter"
              id="filter"
              icon={
                this.state.filterMegaDropdownOpen ? (
                  <ArrowDropUp />
                ) : (
                  <ArrowDropDown />
                )
              }
              name={
                this.state.filterMegaDropdownOpen
                  ? 'filterExpanded'
                  : 'filterCollapsed'
              }
              iconOnRight
              onClick={this.toggleFilterMegaDropdown}
              width="80"
            />,
            <Button
              key="edit"
              label="Edit Parameters"
              icon={<Edit />}
              onClick={openEditParametersModal}
              disabled={selectedIndexes.length === 0}
            />,
            <SelectWithMargin
              instanceId="storeFilter"
              Value={{ label: 'Current', value: true }}
              onChange={this.handleChange}
              options={options}
              placeholder="Store"
            />,
        ]} 

我只想在 isDrodpownShown 为真时显示 SelectwithMargin storeFilter 。所以我尝试添加 if 条件,如下所示。

{isDropDownShown && (
              <SelectWithMargin
              instanceId="storeFilter"
              Value={{ label: 'Current', value: true }}
              onChange={this.handleChange}
              options={options}
              placeholder="Store"
            />
            )}

上面的代码在 && 附近抛出语法错误。我可以知道在反应组件中添加 if 语句的正确方法是什么。任何帮助,将不胜感激。谢谢

标签: reactjs

解决方案


尝试这个。

getDropDown = (isDropDownShown) => {
   if(isDropDownShown){
       return (<SelectWithMargin
              instanceId="storeFilter"
              Value={{ label: 'Current', value: true }}
              onChange={this.handleChange}
              options={options}
              placeholder="Store"
            />);
   }else{
     return (<div></div>);
   }
}


{ this.getDropDown(isDropDownShown) }

推荐阅读