條件渲染根據(jù)博客 8 React conditional rendering methods 有8種寫法饵筑。
茴香豆的茴雖然沒啥用埃篓,但是也可以權(quán)當(dāng)思維拓展。
值得一提的是根资,條件渲染每次條件改變時架专,渲染的內(nèi)容都會被卸載,重新安裝新的條件內(nèi)容玄帕。
if/else
組件級部脚,新建一個子組件,父組件對條件判斷無感裤纹,需要隱藏直接return null
function render() {
if (renderComponent1) {
return <Component1 />;
} else {
return <div />;
}
}
組件變量
變量級委刘,新建一個變量包含條件判斷,渲染變量到j(luò)sx中鹰椒。
function render() {
let component = null;
if (renderComponent1) {
component = <Component1 />;
}
return component;
}
三元運算符
行級锡移,新建一行運算符,直接寫到j(luò)sx中吹零,如果條件簡單最為方便罩抗,不需要新建任何元素。但是嵌套條件下閱讀困難灿椅。
function render() {
return renderComponent1 ? <Component1 /> : null;
}
相似的還有 && 寫法套蒂,如果另一條件返回null可以使用
function render() {
return renderComponent1 && <Component1 />;
}
立即執(zhí)行函數(shù)
函數(shù)級,不多贅述
function render() {
return (
<div>
{(() => {
if (renderComponent1) {
return <Component1 />;
} else {
return <div />;
}
})()}
</div>
);
}
function render() {
return (
<div>
<SubRender />
</div>
);
}
function SubRender() {
if (renderComponent1) {
return <Component1 />;
} else {
return <div />;
}
}
IF組件
外援級茫蛹,做一個條件渲染組件 IF
代替 js 函數(shù)的 if
:
<If condition={true}>
<span>Hi!</span>
</If>
這個組件實現(xiàn)也很簡單
const If = props => {
const condition = props.condition || false;
const positive = props.then || null;
const negative = props.else || null;
return condition ? positive : negative;
};
高階組件
外援級操刀,高階組件,返回一個新組件的函數(shù)婴洼,并且接收一個組件作為參數(shù)骨坑。那么我們就能在高階組件里寫條件語句,返回不同的組件即可:
function higherOrderComponent(Component) {
return function EnhancedComponent(props) {
if (condition) {
return <AnotherComponent {...props} />;
}
return <Component {...props} />;
};
}
總結(jié)
- 當(dāng)項目很簡單,或者條件渲染的邏輯確認(rèn)無法復(fù)用時欢唾,推薦在代碼中用 && 或者三元運算符且警、IIFE 等直接實現(xiàn)條件渲染。
- 當(dāng)項目很復(fù)雜時礁遣,盡量都使用 子函數(shù)斑芜、子組件、IF 組件祟霍、高階組件 等方式做更有抽象度的條件渲染杏头。