简体   繁体   中英

React.js: Add component with value

Just started out learning React.js and I'm trying to build a resusable header that can be in two states; The user logged in || the user NOT logged in.

// Header.js
var Header = React.createClass({

    renderLoggedIn: function() {
        return (
            <div>      
                <a href="index.html">Main</a>
                <a href="user.html">User profile</a>
                <hr/>
            </div>
        );
    }, 
    renderNormal: function() {
        return (
            <div>      
                <a href="index.html">Main</a>
                <a href="login.html">Login</a>
                <hr/>
            </div>
        );
    },
    render: function() {

        if (this.props.type == "normal") {
            return this.renderNormal(); 
        }
        else {
            return this.renderLoggedIn(); 
        }
    }
});

React.render(<Header type="normal" />, document.getElementById('header'))

In the main html file (index.html), I add the header with:

// Index.html
<header id="header"></header>
<script src="src/header.js" type="text/jsx"></script>

I have another file called functions.js, where a isUserLoggedIn() function exists. The return from this function determine whether the user is logged in or not, which should reflect in the header.

// functions.js
function isUserLoggedIn() {
     return // true or false; 
}

Where do I put this logic? Can/should I call the isUserLoggedIn() functions from the React template file? If so, how?

To answer your question the logged in state can be passed as property.

// Header.js
var Header = React.createClass({       

    renderLoggedIn: function() {
        return (
            <div>      
                <a href="index.html">Main</a>
                <a href="user.html">User profile</a>
                <hr/>
            </div>
        );
    }, 
    renderNormal: function() {
        return (
            <div>      
                <a href="index.html">Main</a>
                <a href="login.html">Login</a>
                <hr/>
            </div>
        );
    },
    render: function() {

        if (this.props.isLoggedIn) {
            return this.renderNormal(); 
        }
        else {
            return this.renderLoggedIn(); 
        }
    }
});


React.render(<Header isLoggedIn ={isUserLoggedIn()}/>, document.getElementById('header'))

Properties are immutable so always passed down. Consider using Flux/Reflux for more complex implementations.

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