首页 > 解决方案 > 在渲染方法中创建条件时不显示芯片按钮

问题描述

我正在尝试根据是否单击来呈现特定的芯片按钮。为此,我在包含所有按钮属性的组件状态上设置了一个变量。但是,我在 render 方法中的 if 语句没有显示按钮。但是,当我将它放在 if 语句之外时,它可以工作。

列状态变量的每个元素,是一个芯片按键状态

为了让它工作,我在 render() 上使用了这段代码:

 {
    this.state.columns.find(item => {
       if (item.id === '1'){
         return item.show === true ? (
              <Grid item className={classes.chipWrapper}>
               <Chip
               label='Chip 1'
               color="secondary"
               deleteIcon={<DoneIcon />} 
               id='1'
               onClick={this.handleChip}
               />
             </Grid>
              ) : (
             <Grid item className={classes.chipWrapper}>
               <Chip
               label='Chip 1'
               color="secondary"
               deleteIcon={<DoneIcon />} 
               id='1'
               onClick={this.handleChip}
               />
             </Grid>
         )
       }
    })
  }

这就是我在其余代码中的内容:

class ChipFilter extends React.Component {
  state = {
    anchorEl: null,
    columns: [
      {id: "1", show: false}
    ]
 };

//simply change the property "show" of the column chosen
handleChip = (e) => {
    this.setState(prevState => ({
      columns: prevState.columns.map(
      obj => (obj._id === e.currentTarget.id ? Object.assign(obj, { show: true }) : obj)
    )
   }));
}

无论显示属性如何,我都希望芯片按钮显示在屏幕上,但是材质 ui 应用了不同的设计风格。如果 show 为true,则芯片按钮的显示方式与为false时不同。现在它没有显示芯片按钮。

标签: reactjsmaterial-ui

解决方案


您在渲染中使用 find 的方式不正确。Find 只是返回满足条件的项目。

例如

 var found = items.find(function(item) {
   return item > 10;
 })

改用地图

 this.state.columns.map(item => {
   if (item.id === '1'){
     return (<div> Inside </div>)
   }
 })

推荐阅读