方法一:if、else
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: true
}
}
render() {
if (this.props.isShow) {
return <div>显示</div>;
} else {
return null;
}
}
}
方法二:三元运算符
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: true
}
}
render() {
return this.props.isShow? <div>显示</div> : null;
}
}
方法三:逻辑与 &&
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: true
}
}
render() {
return this.props.isShow && <div>显示</div>;
}
}
方法四:逻辑或 ||
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: true
}
}
render() {
return this.props.isShow || <div>显示</div>;
}
}
方法五:switch、case
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: A
}
}
render() {
switch (this.props.isShow) {
case "A":
return <div> A </div>;
case "B":
return <div> B </div>;
default:
return null;
}
}
}
方法六:枚举值映射
const ComponentMap = {
A: <div>Condition is A</div>,
B: <div>Condition is B</div>,
};
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: A
}
}
render() {
return ComponentMap[this.state.isShow] || null;
}
}
方法七:函数调用
function componentForCondition(condition) {
if (condition === "A") {
return <div>Condition is A</div>;
} else if (condition === "B") {
return <div>Condition is B</div>;
} else {
return null;
}
}
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: A
}
}
render() {
return componentForCondition(this.state.isShow);
}
}
方法八:变量渲染(可以使用变量存储渲染结果,根据不同isShow的值进行条件渲染)
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: A
}
}
render() {
let component = null;
if (this.state.isShow === "A") {
component = <div>Condition is A</div>;
} else if (this.state.isShow === "B") {
component = <div>Condition is B</div>;
}
return component;
}
}