为了账号安全,请及时绑定邮箱和手机立即绑定

返回组件时如何重构&&()

返回组件时如何重构&&()

蝴蝶刀刀 2019-04-25 18:15:10
我最近进入了一个项目,开发人员正在使用这种不熟悉的语法,他们做了类似这样的事情:    {this.props.something === 'Foo' && (       <React.Fragment>        Here       </React.Fragment>     )}我怎么能改写这个呢?

2 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

由于您特别询问了如何重写这些内容,因此在某些情况下您可能会发现一些替代解决方案。

假设您从这样的组件开始:

class MyComp extends Component {
  render() {
    return (
      <div>
        {this.props.something === 'Foo' && (
          <React.Fragment>
            Here
          </React.Fragment>
        )}
      </div>
    );
  }}

你可以把它转换成这个:

class MyComp extends Component {
  render() {
    let content;
    if (this.props.something === 'Foo') {
      content = (
        <React.Fragment>
          Here
        </React.Fragment>
      );
    }
    return (
      <div>{content}</div>
    );
  }}

或这个:

class MyComp extends Component {
  conditionalContent(something) {
    if (something === 'Foo') {
      return (
        <React.Fragment>
          Here
        </React.Fragment>
      );
    }
  }
  render() {
    return (
      <div>
        {this.conditionalContent(this.props.something)}
      </div>
    );
  }}

甚至这个:

const ConditionalComponent = ({ show }) => {
  if (show) {
    return (
      <React.Fragment>
        Here
      </React.Fragment>
    );
  }}class MyComp extends Component {
  render() {
    let content;
    if (this.props.something === 'Foo') {
      content = (
        <React.Fragment>
          Here
        </React.Fragment>
      );
    }
    return (
      <div>
        <ConditionalComponent show={this.props.something === 'Foo'}/>
      </div>
    );
  }}

当然,您还可以提出许多其他变体。这有望让您更多地考虑如何构建组件以获得最佳可读性。


查看完整回答
反对 回复 2019-05-17
?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

由于JavaScript中的短路,整个代码基本上要么false根据条件进行评估

 this.props.something === 'Foo'

未填满,否则(如果条件已满),它将评估到以下React Component实例。由于React会false在渲染过程中过滤出虚假值(包括),如果有foo,这将渲染Fragment,否则它不会呈现任何内容。


查看完整回答
反对 回复 2019-05-17

添加回答

代码语言

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号