如何使用 Facebook React 的 JSX 拥有条件元素并保持 DRY?

2022-01-31 00:00:00 reactjs javascript react-jsx

How do I optionally include an element in JSX? Here is an example using a banner that should be in the component if it has been passed in. What I want to avoid is having to duplicate HTML tags in the if statement.

render: function () {
    var banner;
    if (this.state.banner) {
        banner = <div id="banner">{this.state.banner}</div>;
    } else {
        banner = ?????
    }
    return (
        <div id="page">
            {banner}
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

解决方案

Just leave banner as being undefined and it does not get included.

相关文章