将不同的道具传递给可重用组件时,如何设置道具类型?

时间:2019-10-20 23:07:21

标签: reactjs typescript

我有一个反应打字稿的问题。所以我想从2个不同的父组件中传递不同的props到一个可重用的组件。

import React from 'react'

const ComponentA = () => {
    return (
        <div>
            <ComponentC propA={someprops} propB={someprops} />
        </div>
    )
}

export default ComponentA
import React from 'react'

const ComponentB = () => {
    return (
        <div>
            <ComponentC propC={someprops} propD={someprops} /> // different 
                                                                  props
        </div>
    )
}

export default ComponentB

如何在componentC中设置道具类型以接受那些不同的道具类型?

import React from 'react'

const ComponentC = ({props}: // how to annotate type?) => {
    return (
        <div>
            somecode
        </div>
    )
}

export default ComponentC

谢谢!

1 个答案:

答案 0 :(得分:2)

听起来ComponentC可以接受两组不同的道具。我可能会定义每种组合,然后说道具可以是一种组合,也可以是另一种。例如:

type OptionOneProps = {
  propA: string;
  propB: string;
}

type OptionTwoProps = {
  propC: string;
  propD: string;
}

const ComponentC = (props: OptionOneProps | Option2Props) => {

  ...

}