[英]React: How to conditionally render?
I have three components A, B & C. 我有三个组成部分A,B和C。
I have two flags showA & showB. 我有两个标志showA和showB。
How do i achieve this? 我该如何实现?
You can achieve it in different ways. 您可以通过不同的方式来实现它。
render() {
const { showA, showB } = this.state;
if (showA) return <A />
if (showB) return <B />
return <C />
}
render() {
const { showA, showB } = this.state;
return (
<div>
{(showA && !showB) && <A />}
{(showB && !showA) && <B />}
{(!showA && !showB) && <C />}
</div>
)
}
See also: https://reactjs.org/docs/conditional-rendering.html 另请参阅: https : //reactjs.org/docs/conditional-rendering.html
class APP extends React.Component {
constructor() {
super();
this.state = { showA: false, showB: false };
}
render() {
const {showA, showB} = this.state;
return [showA && <A/>, showB && <B />];
}
}
I guess you meant show C component when showA and showB are both false 我想你的意思是showA和showB都为false时显示C组件
Assuming that your showA and showB are state properties: 假设您的showA和showB是状态属性:
render() {
return (
this.state.showA
? <A />
: this.state.showB ? <B />
: <C />
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.