【问题标题】:What to return in ternary operator in React's JSX when want to return nothing? [duplicate]在 React 的 JSX 中,当什么都不返回时,在三元运算符中返回什么? [复制]
【发布时间】:2021-08-30 18:46:59
【问题描述】:

如果variable 为假,我希望三元运算符的结果不返回任何内容,但我会在分号后面放什么?我确信这里有一个常见的做法,但这是我的临时方法

  render() {
    const { classes } = this.props;
    const variable = this.props.conversation;
    return (
        {variable
          ? (<Box className={classes.chipHolder}>
              <Chip
                label={this.state.numOfUnviewedMessages}
                size="small"
                color="primary"
              />
            </Box>) 
          : (<div/>)
        }
    );
}

【问题讨论】:

标签: javascript reactjs jsx conditional-operator


【解决方案1】:

你可以回null:

class App() {

  render() {
    const { classes } = this.props;
    const variable = this.props.conversation;
    return variable ? (
      <Box className={classes.chipHolder}>
        <Chip
          label={this.state.numOfUnviewedMessages}
          size="small"
          color="primary"
        />
      </Box>
    ) : null)
  }
  
}

来源:https://reactjs.org/docs/conditional-rendering.html#preventing-component-from-rendering

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 2016-05-15
    • 2014-08-03
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2020-12-07
    相关资源
    最近更新 更多