基本上,我有一个react组件,它的render()函数体如下所示:(这是我的理想之一,这意味着它目前不工作)
render(){
return (
<div>
<Element1/>
<Element2/>
// note: logic only, code does not work here
if (this.props.hasImage) <ElementWithImage/>
else <ElementWithoutImage/>
</div>
)
}
你也可以写If语句组件。这是我在我的项目中使用的。
组件/ IfStatement.tsx
import React from 'react'
const defaultProps = {
condition: undefined,
}
interface IfProps {
children: React.ReactNode
condition: any
}
interface StaticComponents {
Then: React.FC<{ children: any }>
Else: React.FC<{ children: any }>
}
export function If({ children, condition }: IfProps): any & StaticComponents {
if (React.Children.count(children) === 1) {
return condition ? children : null
}
return React.Children.map(children as any, (element: React.ReactElement) => {
const { type: Component }: any = element
if (condition) {
if (Component.type === 'then') {
return element
}
} else if (Component.type === 'else') {
return element
}
return null
})
}
If.defaultProps = defaultProps
export function Then({ children }: { children: any }) {
return children
}
Then.type = 'then'
export function Else({ children }: { children: any }) {
return children
}
Else.type = 'else'
If.Then = Then as React.FC<{ children: any }>
If.Else = Else as React.FC<{ children: any }>
export default If
使用的例子:
<If condition={true}>
<If.Then>
<div>TRUE</div>
</If.Then>
<If.Else>
<div>NOT TRUE</div>
</If.Else>
</If>