Home > Article > Web Front-end > What are the different rendering methods of react?
React rendering methods include: 1. Rendering using conditional expressions, suitable for rendering of two components; 2. Rendering using the "&&" operator, suitable for rendering with or without a component; 3. , Use variable output components for rendering; 4. Use functional methods to output components or use functional components for rendering.
The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.
Several ways to conditionally render React components
1. Conditional expression rendering (applicable to two components Rendering of one of the two)
render() { const isLoggedIn = this.state.isLoggedIn; return ( <div> {isLoggedIn ? ( <LogoutButton onClick={this.handleLogoutClick} /> ) : ( <LoginButton onClick={this.handleLoginClick} /> )} </div> ); }
2. && operator rendering (applicable to rendering with or without a component)
function Mailbox(props) { const unreadMessages = props.unreadMessages; return ( <div> <h1>Hello!</h1> {unreadMessages.length > 0 && <h2> You have {unreadMessages.length} unread messages. </h2> } </div> ); }
3. Use variables to output component rendering (suitable for rendering under multiple components and under various conditions)
render() { const isLoggedIn = this.state.isLoggedIn; const button = isLoggedIn ? ( <LogoutButton onClick={this.handleLogoutClick} /> ) : ( <LoginButton onClick={this.handleLoginClick} /> ); return ( <div> <Greeting isLoggedIn={isLoggedIn} /> {button} </div> ); }
4. Use functional methods to output components or use functional components for rendering ( Suitable for situations where multiple sub-components need to be output based on complex conditions)
1. Functional approach
renderButton(){ const isLoggedIn = this.state.isLoggedIn; if(isLoggedIn) { return (<LogoutButton onClick={this.handleLogoutClick} />); } else { return (<LoginButton onClick={this.handleLoginClick} />); } } render() { return ( <div> <Greeting /> {this.renderButton()} </div> ); }
2. Functional component
function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return <UserGreeting />; } return <GuestGreeting />; } ReactDOM.render( // Try changing to isLoggedIn={true}: <Greeting isLoggedIn={false} />, document.getElementById('root') );
[Related recommendations: Redis video tutorial】
The above is the detailed content of What are the different rendering methods of react?. For more information, please follow other related articles on the PHP Chinese website!