我第一次摆弄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);

当前回答

在状态中设置一个布尔值(例如:'show)',然后执行:

var style = {};
if (!this.state.show) {
  style.display = 'none'
}

return <div style={style}>...</div>

其他回答

//use ternary condition

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

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

{ this.state.yourState == 'string' ? <MyComponent /> : ''}

{ this.state.yourState == 'string' && <MyComponent /> }

//Normal condition

if(this.state.yourState){
 return <MyComponent />
}else{
  return null;
}


<button onClick={()=>this.setState({yourState: !this.props.yourState}>Toggle View</button>

一个使用Hooks在React中显示/隐藏元素的简单方法

const [showText, setShowText] = useState(false);

现在,让我们为渲染方法添加一些逻辑:

{showText && <div>This text will show!</div>}

And

onClick={() => setShowText(!showText)}

好工作。

class Toggle extends React.Component {
  state = {
    show: true,
  }

  render() {
    const {show} = this.state;
    return (
      <div>
        <button onClick={()=> this.setState({show: !show })}>
          toggle: {show ? 'show' : 'hide'}
        </button>    
        {show && <div>Hi there</div>}
      </div>
     );
  }
}

如果你想看看如何TOGGLE显示一个组件签出这小提琴。

http://jsfiddle.net/mnoster/kb3gN/16387/

var Search = React.createClass({
    getInitialState: function() {
        return { 
            shouldHide:false
        };
    },
    onClick: function() {
        console.log("onclick");
        if(!this.state.shouldHide){
            this.setState({
                shouldHide: true 
            })
        }else{
                    this.setState({
                shouldHide: false 
            })
        }
    },
render: function() {
    return (
      <div>
        <button onClick={this.onClick}>click me</button>
        <p className={this.state.shouldHide ? 'hidden' : ''} >yoyoyoyoyo</p>
      </div>
    );
}
});

ReactDOM.render( <Search /> , document.getElementById('container'));

React Hooks的简单隐藏/显示示例:(抱歉没有小提琴)

const Example = () => {

  const [show, setShow] = useState(false);

  return (
    <div>
      <p>Show state: {show}</p>
      {show ? (
        <p>You can see me!</p>
      ) : null}
      <button onClick={() => setShow(!show)}>
    </div>
  );

};

export default Example;