Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

javascript - ReactJs - Creating an "If" component... a good idea?

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.

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?

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.

You can check it out here on 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check out the If-Else in JSX section in the react Docs.

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>

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>

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>

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

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...