简体   繁体   English

在React中有条件地渲染组件

[英]Rendering components conditionally in React

I'm conditionally rendering components on the home page based on whether the user is logged in or not. 我有条件地根据用户是否登录在主页上呈现组件。 This is my code, 这是我的代码

class Wrapper extends React.Component{
    constructor(props){
        super(props);
    }
    render(){
        const comp = this.state.loggedIn ? (
            <BrowserRouter>
                <div className="wrapper">
                    <Header state={props.state}/>
                    <CoreLogged state={props.state}/>
                </div>
            </BrowserRouter>

        ):(
            <BrowserRouter>
                <div className="wrapper">
                    <Header state={props.state}/>
                    <CoreUnlogged state={props.state}/>
                </div>
            </BrowserRouter>
        );
        return (comp);
    }
}
export default Wrapper

Since the header component is being rendered irrespective, How can I refactor this code to only render only the Core section conditionally? 由于标头组件的显示方式无关,我该如何重构此代码以仅有条件地仅渲染Core部分? I'm new to React thus the question. 我是React的新手,所以这个问题。

Simply take the stuff that is common and pull it out, then use {} to do the conditional. 只需取出常见的东西并将其拉出,然后使用{}进行条件即可。 You can also just return without the variable: 您也可以不带变量就返回:

render() {
  return <BrowserRouter>
    <div className="wrapper">
      <Header state={ props.state } />
      { this.state.loggedIn ? (
          <CoreLogged state={ props.state } />
        ) : (
          <CoreUnlogged state={ props.state } />
        )
      }
    </div>
  </BrowserRouter>;
}

If the components take the same exact properties, you could alternatively just put that component itself in a variable: 如果组件具有相同的确切属性,则可以选择将该组件本身放在变量中:

render() {
  const MainComp = this.state.loggedIn ? CoreLogged : CoreUnlogged;

  return <BrowserRouter>
    <div className="wrapper">
      <Header state={ props.state } />
      <MainComp state={ props.state } />
    </div>
  </BrowserRouter>;
}

Note that in this case, the variable must start with a capital letter or React will try to render it as a built-in HTML component instead. 请注意,在这种情况下,变量必须以大写字母开头,否则React会尝试将其呈现为内置HTML组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM