react如何不再使用三目运算

之前看了篇文章说react使用一个库就可以不再使用三目运算了,但是现在忘了怎么写的了

阅读 2.2k
3 个回答

react-if

const renderData = (data) => {
  val computed = /* expensive computation */
  return <span>Here is the result: {computed}</span>;
};
 
const Foo = ({ data }) => (
    <div>
        <If condition={false}>
            <Then>{() =>
              renderData(data)
            }</Then>
            <Else>
              Nothing to see here
            </Else>
        </If>
        <If condition={!this.props.bears}>
          <Then>
            No bears
          </Then>
 
          <Else>
            <If condition={() => this.props.bears.length}>
              Empty bears array
            </If>
            <Else>
              // Display bears
            </Else>
          </Else>
        </If>
    </div>
)

自定义一个组件就好了

class Container extends React.Component {
    render() {
        if(!this.props.condition) {
            return null;
        }
        return this.props.children;
    }
}

Container.propTypes = {
    condition: ReactTypes.bool
};

使用

class User extends React.Component {
    render() {
        return (
            <div>
                <Container condition={this.state.logged}>
                未登录
                </Container>
                <Container condition={!this.state.logged}>
                已登录
                </Container>
            </div>
        );
    }
}
新手上路,请多包涵
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题