小编典典

ReactJs-创建一个“ If”组件...一个好主意?

reactjs

我已经在React文档中读到,“如果”类型语句不能在JSX代码中使用,由于JSX呈现到javascript中的方式,它无法正常工作。

但是,有什么理由为什么实现“ if”组件不是一个好主意?从我的初始测试来看,它似乎工作正常,并且使我想知道为什么不经常这样做?

我的部分意图是让反应开发尽可能地基于标记,并且使用尽可能少的javascript。在我看来,这种方法更像是一种“数据驱动”方法。

您可以在JS Fiddle上查看

<script type='text/javascript' src="https://unpkg.com/[email protected]/dist/JSXTransformer.js"></script>

<script type='text/javascript' src="https://unpkg.com/[email protected]/dist/react-with-addons.js"></script>



<script type="text/jsx">

/** @jsx React.DOM */



var If = React.createClass({

  displayName: 'If',



  render: function()

  {

    if (this.props.condition)

      return <span>{this.props.children}</span>

    return null;

  }

});



var Main = React.createClass({

    render: function() {

        return (

           <div>

             <If condition={false}>

                <div>Never showing false item</div>

             </If>

             <If condition={true}>

                <div>Showing true item</div>

             </If>

          </div>

        );

    }

});



React.renderComponent(<Main/>, document.body);

</script>

运行上面的结果是:

显示真实物品


阅读 546

收藏
2020-07-22

共1个答案

小编典典

在react Docs中查看JSX中If-Else部分。

在JSX中,您不能将语句放在大括号中,而只能放在表达式中。如果您不了解JavaScript中表达式与语句之间的区别,请阅读本文。此限制是因为JSX简化了函数调用,并且您不能将if语句用作JavaScript中函数的参数。但是,您可以使用布尔运算符(&&||? :)做类似的工作。它们是表达式,因此可以放入JSX生成的构造函数调用中,并且它们的短路评估与if语句中使用的评估相同。

<div>
    {(true
        ? <div>Showing true item</div>     
        : <div>Never showing false item</div>
    )}
</div>
<p>My name is {this.name || "default name"}</p>

此外,将作出反应治疗nullfalse作为不得到真正的DOM渲染的“空组件”(目前它在后台使用相同的无脚本技巧)。当您不希望使用“
else”分支时,这很有用。有关详细信息,请参见JSX中的False

<div>
    {shouldIncludeChild ? <ChildComponent/> : false}
</div>

至于您所询问的If组件,它的一个问题是即使条件为假,它仍将以其当前形式评估其子级。如果仅在条件为真的情况下才有意义,这可能导致错误:

<If condition={person !== null}>
    //This code throws an exception if this.person is null
    <div>{person.name}</div>
</If>

您可以通过让if组件将主体作为函数而不是作为子组件列表来接收,但其更为冗长,来解决此问题:

<If condition={person !== null} body={function(){
    return <div>{person.name}</div>
}/>

最后,由于If组件是无状态的,您应该考虑使用普通函数而不是新的组件类,因为这会使“ If”对React的对帐算法透明。如果使用If组件,则a
<div>和a <If><div>将被视为不兼容,React将进行完全重绘,而不是尝试将新组件与旧组件合并。

// This custom if function is for purely illustrative purposes
// However, this idea of using callbacks to represent block of code
// is useful for defining your own control flow operators in other circumstances.
function myCustomIf(condition, onTrue, onFalse){
    onTrue  = onTrue  || function(){ return null }        
    onFalse = onFalse || function(){ return null }
    if(condition){
        return onTrue();
    }else{
        return onFalse();
    }
}

<div>    
    {myCustomIf(person !== null, function(){
         return <div>{person.name}</div>
     })}
</div>
2020-07-22