首页 > 解决方案 > 如何动态设置接口以接收共享组件中的道具?

问题描述

我有三个不同的接口,它们作为 props 类型被三个不同的组件接收,事实是,这三个组件是相同的,我只想使用一个组件,但是动态地,它们的值基于接收到的 props。

const UsersOverview: React.FC<{users: Interface[]}> = props => {...}

在 React with JS 中,我只需设置一个 props 并接收值为props.anything,但使用 typescript 我想知道如何动态设置接口:

我有类似的东西:

接口一:

export default interface Interface1{
    id: number,
    name: string,
    companyId: number
}

接口二:

export default interface Interface2 {
    id: number,
    email: string,
    name: string,
    unitId: number,
    companyId: number
}

接口3:

export default interface Interface3 {
    id: number | null,
    name: string | null
}

我的子组件是这样的(我正在使用Interface3,但我想动态设置它):

import React from 'react'

import Interface1 from '/models/Interface3'


const CompanyOverview: React.FC<{company: Interface3}> = props => {
    let [companyName, setCompanyName] = React.useState<string | null>('')

    React.useEffect(() => {
        setCompanyName(props.company.name)        
    }, [props.company])

    return (
        <div>
           <p>Contratante: {companyName}</p>
        </div>
    )
}

export default CompanyOverview

标签: javascriptreactjstypescripttypesinterface

解决方案


推荐阅读