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