短篇 React 學習筆記。
Conditional Rendering
Conditional Rendering = make things happen with certain conditions
Common ways in React are…
- If..else statement
- Element variables
- Ternary operators
- Logical && operators
- Prevent rendering with null
If…else
1
2
3
4
5
| if(isLoggedIn) {
return <button> Logout </button>
} else {
return <button> Login </button>
}
|
Element Variables
1
2
3
4
5
6
7
8
9
| if(isLoggedIn) {
Button = <button> Logout </button>;
} else {
Button = <button> Login </button>;
}
return(
<div>{ Button }</div>
);
|
Ternary operators
1
2
3
4
5
6
7
| <div>
{
isLoggedIn ?
<button> Logout </button> :
<button> Login </button>
}
</div>
|
Logical && operators
1
2
3
4
5
6
7
8
| <div>
{
isLoggedIn && <button> Logout </button>
}
{
!isLoggedIn && <button> Login </button>
}
</div>
|
Prevent rendering with null
1
2
3
4
5
| if(isLoggedIn) {
return <button> Logout </button>
} else {
return null;
}
|