在 React 和 TypeScript (TSX) 中实现类似 Vue 中的 v-if
功能,可以使用条件渲染。React 提供了多种方式来进行条件渲染,下面是一些常见的方法:
方法一:使用三元运算符
三元运算符是最常见和直接的方法,适用于简单的条件渲染。
import React from 'react';
interface MyComponentProps {
showContent: boolean;
}
const MyComponent: React.FC<MyComponentProps> = ({ showContent }) => {
return (
<div>
{showContent ? (
<div>Content is shown</div>
) : (
<div>Content is hidden</div>
)}
</div>
);
};
export default MyComponent;
方法二:使用逻辑与 (&&
) 运算符
逻辑与运算符适用于只在条件为真时才显示内容的情况。
import React from 'react';
interface MyComponentProps {
showContent: boolean;
}
const MyComponent: React.FC<MyComponentProps> = ({ showContent }) => {
return (
<div>
{showContent && <div>Content is shown</div>}
</div>
);
};
export default MyComponent;
方法三:使用 IIFE(立即调用函数表达式)
对于更复杂的逻辑,你可以使用 IIFE 来进行条件渲染。
import React from 'react';
interface MyComponentProps {
showContent: boolean;
}
const MyComponent: React.FC<MyComponentProps> = ({ showContent }) => {
return (
<div>
{(() => {
if (showContent) {
return <div>Content is shown</div>;
} else {
return <div>Content is hidden</div>;
}
})()}
</div>
);
};
export default MyComponent;
方法四:条件渲染函数
如果条件渲染的逻辑比较复杂,可以将其封装到一个函数中。
import React from 'react';
interface MyComponentProps {
showContent: boolean;
}
const MyComponent: React.FC<MyComponentProps> = ({ showContent }) => {
const renderContent = () => {
if (showContent) {
return <div>Content is shown</div>;
}
return <div>Content is hidden</div>;
};
return (
<div>
{renderContent()}
</div>
);
};
export default MyComponent;
方法五:使用子组件
通过将条件渲染逻辑放到子组件中,可以使主组件更加简洁。
import React from 'react';
interface ContentProps {
showContent: boolean;
}
const Content: React.FC<ContentProps> = ({ showContent }) => {
if (showContent) {
return <div>Content is shown</div>;
}
return <div>Content is hidden</div>;
};
const MyComponent: React.FC<ContentProps> = ({ showContent }) => {
return (
<div>
<Content showContent={showContent} />
</div>
);
};
export default MyComponent;
总结
在 React 和 TSX 中实现类似 Vue 中的 v-if
功能,可以使用三元运算符、逻辑与运算符、IIFE、条件渲染函数或者子组件。这些方法都可以根据具体需求进行选择和组合使用。以下是一个综合的例子:
import React from 'react';
interface MyComponentProps {
showContent: boolean;
}
const MyComponent: React.FC<MyComponentProps> = ({ showContent }) => {
return (
<div>
{showContent && <div>Content is shown</div>}
{!showContent && <div>Content is hidden</div>}
</div>
);
};
export default MyComponent;