在React中显示或隐藏元素

我第一次弄乱React.js,找不到通过click事件在页面上显示或隐藏内容的方法。我没有在页面上加载任何其他库,因此我正在寻找使用React库的本机方法。到目前为止,这就是我所拥有的。当点击事件触发时,我想显示结果div。


var Search= React.createClass({

    handleClick: function (event) {

        console.log(this.prop);

    },

    render: function () {

        return (

            <div className="date-range">

                <input type="submit" value="Search" onClick={this.handleClick} />

            </div>

        );

    }

});


var Results = React.createClass({

    render: function () {

        return (

            <div id="results" className="search-results">

                Some Results

            </div>

        );

    }

});


React.renderComponent(<Search /> , document.body);


收到一只叮咚
浏览 4334回答 3
3回答

慕神8447489

<style type="text/css">&nbsp; &nbsp; .hidden { display:none; }</style>render: function() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div className={this.props.shouldHide ? 'hidden' : ''}>&nbsp; &nbsp; &nbsp; &nbsp; This will be hidden if you set <tt>props.shouldHide</tt>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; to something truthy.&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );}// or in more modern JS and stateless reactconst Example = props => <div className={props.shouldHide}/>Hello</div>

largeQ

这是三元运算符的另一种语法:{ this.state.showMyComponent ? <MyComponent /> : null }等效于:{ this.state.showMyComponent && <MyComponent /> }精益为何以及其他语法 display: 'none';<MyComponent style={this.state.showMyComponent ? {} : { display: 'none' }} />但是,如果您使用过度display: 'none',则会导致DOM污染,并最终减慢您的应用程序的速度。
打开App,查看更多内容
随时随地看视频慕课网APP