简体   繁体   中英

React pass component as react

I am wanting to pass a component to another component as prop, the component needs to change based on whether or not the user is authenticated, in the example below my component is rendering, but the component passed via the navigation prop is not,

import React from 'react';
import { render } from 'react-dom';

import Layout from './core/Layout';

import LoggedInHeader from './core/LoggedInHeader';
import LoggedOutHeader from './core/LoggedOutHeader';

const authenticated = false;

const App = () => (
  <div>
    <Layout navigation={() => authenticated ? <LoggedInHeader /> : <LoggedOutHeader /> } />
  </div>
);

render(<App />, document.getElementById('root'));

If I do,

<Layout navigation={<LoggedInHeader />} />

It works fine, but I need to show a logged out user a different navigation bar.

You dont need the action binding ()=>{}

Just do it like this

 <Layout navigation={ authenticated ? <LoggedInHeader /> : <LoggedOutHeader /> } />

您应该能够做到这一点

<Layout navigation={authenticated ? <LoggedInHeader /> : <LoggedOutHeader /> } />

I feel like the 'cleaner' approach will be to pass boolean as prop to the Layout component (eg <Layout authenticated={authenticated} ).

Then in the Layout component you return (or render):

<div>
  {this.props.authenticated ? (
    <LoggedInHeader />
  ) : (
    <LoggedOutHeader />
  )}
</div>

I assume your layout component is more complicated (it's a container), so it's better to let it decide what should be rendered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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