如何在箭头功能中进行条件渲染?

时间:2020-07-21 08:22:51

标签: javascript reactjs arrow-functions

我是箭头功能的新手,我正在为用户开发一个应用程序,并且我正在使用React模板,因为在我的应用程序中也有登录和注销系统,并且我将注销按钮放在该模板的页脚中,我正面临着问题是,每当用户访问网站,然后在登录之前,用户会看到注销按钮,因为该按钮位于页脚中,所以我想要的是根据会话中存储的电子邮件消失注销按钮,这意味着会话中是否有用户电子邮件,然后注销按钮出现在页脚中,否则用户看不到注销按钮是页脚的代码

import React from 'react';
import PropTypes from 'prop-types';
const email = session.getitem('user.email');
const FooterText = (props) => (

    
    
    
    <React.Fragment>

    
<br/><br/>
 <div className="hr-text hr-text-center my-2" > 
// i want to put check here that if session have user email then show that button other vise disappear
<button onClick={logout}>Logout</button> 
 </div> 


        &copy; { props.year } All Rights Reserved. 
        Designed and implemented by{' '}
        <a
            href="http://aliraza"
            target="_blank"
            rel="noopener noreferrer"
            className="sidebar__link"
        >
            ali raza
        </a>
    </React.Fragment>
)
FooterText.propTypes = {
    year: PropTypes.node,
    name: PropTypes.node,
    desc: PropTypes.node,
};
FooterText.defaultProps = {
    year: "2020",
    name: "Admin Theme",
    desc: "Bootstrap 4, React 16 (latest) & NPM"
};

export { FooterText };

我想在这里检查一下,如果会话中有用户电子邮件,则表明其他老虎钳按钮消失了,但是在箭头功能中,我正在努力使用if else语句我们该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以像下面那样应用检查,可以使用三元运算符检查条件

 import React from 'react';
import PropTypes from 'prop-types';
const email = session.getitem('user.email');
const FooterText = (props) => (

    
    
    
    <React.Fragment>

    
<br/><br/>
 <div className="hr-text hr-text-center my-2" > 
// i want to put check here that if session have user email then show that button other vise disappear
{email?(<button onClick={logout}>Logout</button>):null} 
 </div> 


        &copy; { props.year } All Rights Reserved. 
        Designed and implemented by{' '}
        <a
            href="http://aliraza"
            target="_blank"
            rel="noopener noreferrer"
            className="sidebar__link"
        >
            ali raza
        </a>
    </React.Fragment>
)
FooterText.propTypes = {
    year: PropTypes.node,
    name: PropTypes.node,
    desc: PropTypes.node,
};
FooterText.defaultProps = {
    year: "2020",
    name: "Admin Theme",
    desc: "Bootstrap 4, React 16 (latest) & NPM"
};

export { FooterText };

答案 1 :(得分:2)

您可以尝试使用React的方式:

{condition && <button onClick={logout}>Logout</button>}

如果条件为true,它将显示按钮,否则将不显示任何内容。

React Conditinal Rendering