【问题标题】:How to setup prop type when passing in different props to a re-usable component?将不同的道具传递给可重用组件时如何设置道具类型?
【发布时间】:2019-10-20 23:07:21
【问题描述】:

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

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 中设置 prop 类型以接收这些不同的 prop 类型?

import React from 'react'

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

export default ComponentC

谢谢!

【问题讨论】:

  • 每个父组件将使用您传递给它们的唯一道具呈现它们自己的&lt;ComponentC&gt; 实例。您在哪里遇到问题?
  • 如果ComponentC 可以有任何道具,props: any 可能是一个选项。我认为对问题的描述不够充分,无法提供更好的建议。

标签: reactjs typescript


【解决方案1】:

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

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

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

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

  ...

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 2017-10-03
    • 2018-07-07
    • 2018-12-14
    相关资源
    最近更新 更多