在 React 中使用 TypeScript 联合类型进行条件渲染是一个好方法吗?

问题描述 投票:0回答:1

我目前正在开发一个 React 项目,我需要根据从服务器接收到的数据类型来渲染不同的组件。我决定使用 TypeScript 联合类型来管理各种类型项目的不同数据结构,包括项目、新闻、模因和图库项目。

这是 React 中处理基于数据类型的条件渲染的最佳方法吗?在实现此类组件时,我应该考虑更好的实践或改进吗?

预先感谢您的见解!

我的组件代码:

import React from 'react';

interface ProjectRowBase {
    type: "projects" | "news" | "memes" | "gallery";
    id: number,
    onApprove: () => void;
    onReject: () => void;
}

interface ProjectsData extends ProjectRowBase {
    type: "projects",
    title: string,
    owner: string,
    description: string
}

interface NewsData extends ProjectRowBase {
    type: 'news',
    title: string,
    date: string,
    description: string,
    author: string,
    image: string
}

interface MemesData extends ProjectRowBase {
    type: "memes",
    image: string,
    owner: string
}

interface GalleryData extends ProjectRowBase {
    type: "gallery",
    image: string,
    owner: string
}

type ProjectRowProps = ProjectsData | NewsData | MemesData | GalleryData;

const ProjectRow: React.FC<ProjectRowProps> = (props) => {
    if (props.type === "projects") {
        return (
            <div className="projectsRow">
                <p>{props.id}</p>
                <h3>Project: {props.title}</h3>
                <p>Owner: {props.owner}</p>
                <p>Description: {props.description}</p>
                <div className="actions">
                    <button onClick={props.onReject}>Reject</button>
                    <button onClick={props.onApprove}>Approve</button>
                </div>
            </div>
        );
    }
    // Similar blocks for other types (news, gallery, memes)
};

export default ProjectRow;
reactjs typescript
1个回答
0
投票

这实际上很棒,但要考虑的是如果没有条件会渲染什么。

© www.soinside.com 2019 - 2024. All rights reserved.