我第一次摆弄React.js,找不到一种方法通过单击事件在页面上显示或隐藏一些东西。我没有加载任何其他库到页面,所以我正在寻找一些使用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);

当前回答

下面是三元操作符的另一种语法:

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

等价于:

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

学习的原因


还有显示的替代语法:'none';

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

然而,如果你过度使用display: 'none',这将导致DOM污染,并最终降低应用程序的速度。

其他回答

我从React团队的声明开始:

在React中,你可以创建封装行为的不同组件 你所需要的。然后,您只能渲染其中的一些,这取决于 您的申请状态。 条件渲染在React中的工作方式与条件的工作方式相同 JavaScript。使用JavaScript操作符,如if或条件 运算符来创建表示当前状态的元素,并让 React更新UI以匹配它们。

基本上需要显示组件的按钮被点击时,你可以两种方式,使用纯粹的反应或使用CSS,使用纯的反应方式,你可以做类似下面的代码在你的情况下,所以在第一次运行,结果并不像hideResults显示是正确的,但通过单击按钮,状态会改变和hideResults是假和组件再次呈现新的价值条件下,这是很常见的使用改变组件视图的反应……

var Search = React.createClass({
  getInitialState: function() {
    return { hideResults: true };
  },

  handleClick: function() {
    this.setState({ hideResults: false });
  },

  render: function() {
    return (
      <div>
        <input type="submit" value="Search" onClick={this.handleClick} />
        { !this.state.hideResults && <Results /> }
      </div> );
  }

});

var Results = React.createClass({
  render: function() {
    return (
    <div id="results" className="search-results">
      Some Results
    </div>);
   }
});

ReactDOM.render(<Search />, document.body);

如果你想进一步研究React中的条件渲染,可以看看这里。

下面是三元操作符的另一种语法:

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

等价于:

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

学习的原因


还有显示的替代语法:'none';

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

然而,如果你过度使用display: 'none',这将导致DOM污染,并最终降低应用程序的速度。

使用rc-if-else模块

npm install --save rc-if-else
import React from 'react';
import { If } from 'rc-if-else';

class App extends React.Component {
    render() {
        return (
            <If condition={this.props.showResult}>
                Some Results
            </If>
        );
    }
}

如果你使用bootstrap 4,你可以用这种方式隐藏元素

className={this.state.hideElement ? "invisible" : "visible"}

在最新的react 0.11版本中,你也可以只返回null,不呈现任何内容。

渲染为空