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

当前回答

//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>

其他回答

这也可以像这样实现(非常简单的方法)

 class app extends Component {
   state = {
     show: false
   };
 toggle= () => {
   var res = this.state.show;
   this.setState({ show: !res });
 };
render() {
  return(
   <button onClick={ this.toggle }> Toggle </button>
  {
    this.state.show ? (<div> HELLO </div>) : null
  }
   );
     }

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

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

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

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

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

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

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

And

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

好工作。

使用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>
        );
    }
}

在react中隐藏和显示元素是非常简单的。

有很多种方法,但我只展示两种。

方式1:

const [isVisible, setVisible] = useState(false)

let onHideShowClick = () =>{
    setVisible(!isVisible)
}

return (<div> 
        <Button onClick={onHideShowClick} >Hide/Show</Button>
         {(isVisible) ? <p>Hello World</p> : ""}
</div>)

方式2:

const [isVisible, setVisible] = useState(false)

let onHideShowClick = () =>{
    setVisible(!isVisible)
}

return (<div> 
        <Button onClick={onHideShowClick} >Hide/Show</Button>
        <p style={{display: (isVisible) ? 'block' : 'none'}}>Hello World</p>
</div>)

它就像if和else一样工作。

在方法一中,它将删除并重新渲染Dom中的元素。 在第二种方式中,你只是将元素显示为false或true。

谢谢你!