React條件渲染的方式

2021-08-18 20:23:14 字數 2497 閱讀 4902

三元操作符(ternary operator)

邏輯 && 操作符

switch.. case.. 語句

列舉(enums)

多層條件渲染(multi-level conditional reandering)

使用高階元件

if (!list)

return (

/>)}

div>

);}

function

list

() // list 為空的情況

if (!list.length) else

);}}

const iseditmode = mode === 'edit';

return (

/>

: item=>

}div>

);}

function

loadingindicator

() else

}

function

loadingindicator

()

);}

function

loadingindicator

() );

}

function notification()  />;

case

'warning':

return

text= />;

case

'info':

return

text= />;

default:

return null;

}}

notification.proptypes =
function notification() 

})()}

div>

);}

const enum = ;
function notification()  />,

warning: text= />,

error: text= />

}[state]}

)}

const notification_states = ;

function

notification()

)}

info: text= />,

warning: text= />,

error: text= />,

});function notification()

div>

)}

function foobarorfooorbar() -$`;

return (

[key]}

);}foobarorfooorbar.proptypes =

function

list

() )});

}// 例項

list= /> //

list= /> // sorry, the list is empty

list= /> // abc

但是最好保持巢狀的層數最小化,這樣**可讀性更強。可以將元件劃分成更小的元件的方式

function

list

() : list} isempty= />});

}function

nolist

()

function

withloadingindicator

(component) )

return

loading...

; }

}// 使用

const listwithloadingindicator = withloadingindicator(list);

最簡單的條件渲染 

適用於新手 

使用if,從渲染方法中返回null提前退出函式

比if-else更好,優先使用 

比if-else更加簡潔 

邏輯 『&&』 操作符 

不返回元素就返回null時使用

比較冗長 

可以通過立即呼叫函式內聯使用 

使用列舉的方式代替這種方式更好

使用於不同的狀態使用 

超過一種條件選擇時使用

避免使用這種方式對可讀性的影響 

將元件劃分為更小的元件,小組件自身帶有條件選擇 

偏向於使用高階元件(hocs) 

hocs

元件能關注主要的邏輯目的

React條件渲染

在乙個新的元件內根據不同的條件返回不同內容的元件 function greeting props return 將元素存入乙個變數,作為變數表示式再渲染 let button null if isloggedin else 當條件滿足再渲染,true expression總是會返回expressio...

react條件列表渲染

條件渲染 1.條件判斷 constructor props render else return 封裝到函式中 constructor props render gettitlejsx else return titlejsx 2.三元運算子class extends react.component...

React學習 條件渲染 列表渲染 表單渲染

如下 lang en charset utf 8 name viewport content width device width,initial scale 1.0 documenttitle head div body src crossorigin script src crossorigin...