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
640 views
in Technique[技术] by (71.8m points)

reactjs - way to embed if expressions inside JSX code?

I guess that stuff that goes into a react tag must be a react tag or a string; a function that returns a tag or string; a collection of tag or string or functions that return them.

So the if statement here is not valid:

return <div> 
        if(something){
           <ProjectType typ={this.state.type} onChange={this.changeType}/>
        }
        And the choice is {type[this.state.type]}
      </div>;

So the obvious way is to move that if expression into a function maybe_render that returns the tag when the condition is met.

return <div> 
        maybe_render(something, this.state.type, this.changeType)
        And the choice is {type[this.state.type]}
      </div>;

Problem is, some snippets will have lots of calls to functions that have very little logic. Instead of a 5-line snippet, we may have a 5-line snippet with many calls to extremely small functions.

What is a good way to embed if expressions inside JSX code?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I usually do ternary if statements if there's not much logic or cause for re-use:

return (
    <div>
        {doSomething ? something : null}
        Something else
    </div>
);

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

...