Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 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 Answer

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>
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...