为了账号安全,请及时绑定邮箱和手机立即绑定

在React中显示或隐藏元素

在React中显示或隐藏元素

收到一只叮咚 2019-10-14 10:24:22
我第一次弄乱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);
查看完整描述

3 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

<style type="text/css">

    .hidden { display:none; }

</style>

render: function() {

    return (

      <div className={this.props.shouldHide ? 'hidden' : ''}>

        This will be hidden if you set <tt>props.shouldHide</tt> 

        to something truthy.

      </div>

    );

}


// or in more modern JS and stateless react

const Example = props => <div className={props.shouldHide}/>Hello</div>


查看完整回答
反对 回复 2019-10-14
?
largeQ

TA贡献2039条经验 获得超7个赞

这是三元运算符的另一种语法:


{ this.state.showMyComponent ? <MyComponent /> : null }

等效于:


{ this.state.showMyComponent && <MyComponent /> }

精益为何


以及其他语法 display: 'none';


<MyComponent style={this.state.showMyComponent ? {} : { display: 'none' }} />

但是,如果您使用过度display: 'none',则会导致DOM污染,并最终减慢您的应用程序的速度。


查看完整回答
反对 回复 2019-10-14
  • 3 回答
  • 0 关注
  • 4308 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信