React conditional rendering
In some cases, the content of the interface will display different content according to different situations, or decide whether to render a certain part of the content:
In vue, we will control it through instructions: such as v-if, v-show;
In React, all conditional judgments are the same as normal JavaScript code;
What are the common ways of conditional rendering?
Method 1: Conditional judgment statement judgment, suitable for situations with more logic
class App extends React.Component {
constructor() {
super()
this.state = {
isShow: true
}
}
render() {
const {
isShow } = this.state
let showElement = null
// 条件判断语句决定显式的内容
if (isShow) {
showElement = <h2>哈哈哈</h2>
} else {
showElement = <h2>呵呵呵</h2>
}
return (
<div>
{
/* 方式一: 条件判断语句 */}
{
showElement}
</div>
)
}
}
const app = ReactDOM.createRoot(document.querySelector("#app"))
app.render(<App/>)
Method 2: Ternary operator judgment, suitable logic is relatively simple
class App extends React.Component {
constructor() {
super()
this.state = {
isShow: true
}
}
render() {
const {
isShow } = this.state
}
return (
<div>
{
/* 方式二: 三元运算符判断 */}
<div>{
isShow ? <h2>我是标题</h2> : <p>我是内容</p> }</div>
</div>
)
}
}
const app = ReactDOM.createRoot(document.querySelector("#app"))
app.render(<App/>)
Method 3: ( similar to the effect of v-if in Vue ) logical AND operator &&, suitable for rendering a component if the condition is true; if the condition is not true, nothing is rendered;
For example, the following code indicates that the student will only be rendered when there is a value, and nothing will be rendered if there is no value.
class App extends React.Component {
constructor() {
super()
this.state = {
student: {
firstName: "chen",
lastName: "yq"
}
}
}
render() {
const {
student } = this.state
return (
<div>
{
/* 方式三: 逻辑与运算符 */}
<div>{
student && <h2>{
student.firstName + " " + student.lastName}</h2>}</div>
</div>
)
}
}
const app = ReactDOM.createRoot(document.querySelector("#app"))
app.render(<App/>)
The effect of v-show
Mainly to control whether the display property is none, the effect of v-show can also be achieved in React
class App extends React.Component {
constructor() {
super()
this.state = {
isShow: true
}
}
render() {
const {
isShow } = this.state
return (
<div>
{
/* v-show的效果, 切换display */}
<h2 style={
{
display: isShow ? "block" : "none"}}>哈哈哈</h2>
</div>
)
}
}
const app = ReactDOM.createRoot(document.querySelector("#app"))
app.render(<App/>)