ReactJs - 创建“如果”组件......一个好主意? [英] ReactJs - Creating an "If" component... a good idea?

查看:76
本文介绍了ReactJs - 创建“如果”组件......一个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React文档中读到if类​​型语句不能在JSX代码中使用,因为JSX呈现为javascript的方式,它不会像人们期望的那样工作。

I've read in the React docs that "if" type statements can't be used in JSX code, because of the way JSX renders into javascript, it doesn't work out as one would expect.

但有没有理由为什么实施if组件是一个坏主意?它似乎从我最初的测试中运行良好,让我想知道为什么不经常这样做?

But is there any reason why implementing an "if" component is a bad idea? It seems to work fine from my initial tests, and makes me wonder why this isn't done more often?

我的部分目的是尽可能地让反应开发尽可能地基于标记 - 尽可能少的javascript。对我而言,这种方法更像是一种数据驱动的方法。

Part of my intent is to allow react development to be as much as possible, markup based - with as little javascript as possible. This approach, to me, feels like more of a "data driven" approach.

你可以在JS Fiddle上查看

<script type='text/javascript' src="https://unpkg.com/react@0.11.0/dist/JSXTransformer.js"></script>
<script type='text/javascript' src="https://unpkg.com/react@0.11.0/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>

运行以上结果:


显示真实物品

Showing true item


推荐答案

查看 JSX中的If-Else 部分。

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

In JSX, you can't put statements inside curly braces--only expressions. If you don't know the difference between expressions vs statements in JavaScript read this article. This limitation is because JSX desugars into function calls and you can't use if-statements as arguments to a function in JavaScript. However, you can use boolean operators (&&, || and ? :) to do a similar job. They are expressions so they can fit inside the constructor calls JSX generates and their short-circuiting evaluation is the same as the one used in if statements.

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

此外,React将处​​理 null false 作为空组件,不会在真实DOM中呈现(目前它在幕后使用相同的noscript技巧)。当您不想要else分支时,这很有用。有关详细信息,请参阅 JSX中的错误

Additionally, React will treat null and false as an "empty component" that does not get rendered in the real DOM (currently it uses that same noscript trick behind the scenes). This is useful when you don't want an "else" branch. See False in JSX for details.

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






至于你询问的If组件,问题在于它的当前形式即使条件是假的,它也会评估它的孩子。如果条件为真,那么当If的主体才有意义时,这可能会导致错误:


As for the If component you asked about, one problem it has is that in its current form it will evaluate its children even if the condition is false. This can lead to errors when the body of the If only makes sense if the condition is true:

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

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

You could workaround this by having the if component receive the body as a function instead of as a list of child components but its more verbose:

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

最后,由于If组件是无状态的,你应该考虑使用普通函数而不是新组件class,因为这会使If对React的协调算法透明。如果您使用If组件,那么< div> < If>< div> 将会被认为是不兼容的,React将完全重绘,而不是尝试将新组件与旧组件合并。

Finally, since the If component is stateless, you should consider using a plain function instead of a new component class, as this would make the "If" transparent to React's reconciliation algorithm. If you use an If component, then a <div> and a <If><div> will be considered incompatible and React will do a full redraw instead of trying to merge the new component with the old one.

// 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>

这篇关于ReactJs - 创建“如果”组件......一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆