React.js 中的條件渲染
使用條件語句可以渲染和移除特定的元件。條件處理在 JavaScript 和 React.js 中的工作方式類似。
示例
function DisplayUserMessage( props ){
const user = props.user.type;
if(type==’Player’){
return <h1>Player </player>;
}
If( type==’Admin’){
Return <h1>Admin </h1>;
}
}在上面的示例中使用了 if 語句。使用者的型別決定了要返回哪條訊息。
元件的區域性狀態在決定條件渲染時很有用,因為狀態可以靈活地在元件內發生變化。
帶有邏輯運算子 && 的行內 if
function MessageSizeChecker(props) {
const message = props.message;
return (
<div>
<h1>Hello!</h1>
{message.length > 100 &&
<h2>
Message size is greater than 100
</h2>
}
</div>
);
}如果 && 運算子的第一個引數計算結果為 true,則第二個引數會在螢幕上呈現。
帶有三元運算子的行內 if else —
它的語法如下:condition ? ‘ first’ : ‘second’;
function MessageSizeChecker(props) {
const message = props.message;
return (
<div>
<h1>Hello!</h1>
{message.length > 100 ? ‘Message size is greater than 100’: ‘Message size is ok’}
</div>
);
}在多個塊語句上可以使用此三元表示式,但它會變得不容易理解。因此為了讓它變得簡單,它應該用於簡單的條件。
我們可以決定呈現哪一個元件。
render() {
const isPlayer = this.state.user.isPlayer;
return (
<div>
{ isPlayer ? (
<Player >
) : (
<Admin />
)
}
</div>
);
}要防止元件進行渲染,我們也可以返回一個 null。但僅僅在 render 方法中返回 null 不會阻止 React 的後續適用的生命週期。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP