ตอบสนองการแสดงผลแบบมีเงื่อนไข
ใน React คุณสามารถแสดงส่วนประกอบตามเงื่อนไขได้
มีหลายวิธีในการทำเช่นนี้
if
คำให้การ
เราสามารถใช้ตัวif
ดำเนินการ JavaScript เพื่อตัดสินใจว่าจะแสดงผลองค์ประกอบใด
ตัวอย่าง:
เราจะใช้สององค์ประกอบนี้:
function MissedGoal() {
return <h1>MISSED!</h1>;
}
function MadeGoal() {
return <h1>Goal!</h1>;
}
ตัวอย่าง:
ตอนนี้ เราจะสร้างส่วนประกอบอื่นที่เลือกส่วนประกอบที่จะแสดงผลตามเงื่อนไข:
function Goal(props) {
const isGoal = props.isGoal;
if (isGoal) {
return <MadeGoal/>;
}
return <MissedGoal/>;
}
ReactDOM.render(
<Goal isGoal={false} />,
document.getElementById('root')
);
ลองเปลี่ยนisGoal
แอตทริบิวต์เป็นtrue
:
ตัวอย่าง:
ReactDOM.render(
<Goal isGoal={true} />,
document.getElementById('root')
);
&&
ตัว ดำเนินการเชิงตรรกะ
อีกวิธีหนึ่งในการแสดงองค์ประกอบ React แบบมีเงื่อนไขคือการใช้ตัว&&
ดำเนินการ
ตัวอย่าง:
เราสามารถฝังนิพจน์ JavaScript ใน JSX โดยใช้วงเล็บปีกกา:
function Garage(props) {
const cars = props.cars;
return (
<>
<h1>Garage</h1>
{cars.length > 0 &&
<h2>
You have {cars.length} cars in your garage.
</h2>
}
</>
);
}
const cars = ['Ford', 'BMW', 'Audi'];
ReactDOM.render(
<Garage cars={cars} />,
document.getElementById('root')
);
ถ้าcars.length
เท่ากับ true นิพจน์ after &&
จะแสดงออกมา
ลองล้างcars
อาร์เรย์:
ตัวอย่าง:
const cars = [];
ReactDOM.render(
<Garage cars={cars} />,
document.getElementById('root')
);
ผู้ประกอบการ Ternary
อีกวิธีหนึ่งในการแสดงองค์ประกอบตามเงื่อนไขคือการใช้ตัวดำเนินการ ternary
condition ? true : false
เราจะกลับไปที่ตัวอย่างเป้าหมาย
ตัวอย่าง:
ส่งคืนMadeGoal
ส่วนประกอบ if
isGoal
is true
มิฉะนั้นให้ส่งคืนMissedGoal
ส่วนประกอบ:
function Goal(props) {
const isGoal = props.isGoal;
return (
<>
{ isGoal ? <MadeGoal/> : <MissedGoal/> }
</>
);
}
ReactDOM.render(
<Goal isGoal={false} />,
document.getElementById('root')
);
หากต้องการเรียนรู้เพิ่มเติม ให้ดูส่วนโอเปอเรเตอร์ประกอบ