【问题标题】:React with Typescript defaultProps an array of object与 Typescript 反应 defaultProps 对象数组
【发布时间】:2018-09-24 13:48:21
【问题描述】:

我正在尝试为对象 prop 数组的某些字段设置 defaultProps。

interface IProps {
  steps: Array<{
    id: number | string
    route?: string
    label?: string
    completed?: boolean
    disabled?: boolean
    active?: boolean
  }>
}


class Stepper extends React.Component<IProps, {}> {
  static defaultProps: IProps = {
    steps: ???
  }
  render() {
    return <div></div>
  }
}

我尝试在网上查找,但找不到为我的案例设置 defaultProps 的方法。

我想只为completeddisabledactive 设置一些默认值,而让其他保持不变。

有没有简单的方法可以做到这一点?

【问题讨论】:

  • 可能,用completeddisabledactive 成员声明接口ISomeOfIProps。并定义defaultProps: ISomeOfIProps? :)
  • 我对带有 React 的 Typescript 有点陌生(仅来自 JS),您介意为我设置一个示例吗?我将不胜感激!

标签: reactjs typescript react-native


【解决方案1】:

我会提取接口IStep,并将其拆分为partialcomplete一个:

interface IPartialStep {
  completed?: boolean
  disabled?: boolean
  active?: boolean
}

interface IStep extends IPartialStep {
  id: number | string
  route?: string
  label?: string
};

所以,现在使用 2 个组件是合乎逻辑的:步骤列表 (Stepper) 和步骤项目 (Step):

interface IProps {
  steps: Array<IStep>
}

class Stepper extends React.Component<IProps, {}> {
  // actually, default props are moved to Step
  // so this one probably not needed.
  static defaultProps: IProps = {
    steps: []
  }
  render() {
    return this.props.steps.map(step => <Step {...step}/>);
  }
}

class Step extends React.Component<IStep> {
  static defaultProps: IPartialStep = {
    // here you can define default props for step item
    completed: false,
    disabled: false,
    active: false,
  }
  render() {
    const {id, route, ...} = this.props;
    // here you define how to display every step
    return <div>{id}</div>
  }
}

希望对你有帮助。

【讨论】:

  • 太棒了,这正是我需要的!现在我知道当我遇到这样的情况时我需要拆分我的组件!感谢您的帮助!
猜你喜欢
  • 2016-09-12
  • 2023-01-24
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-26
  • 2020-06-13
  • 2018-05-06
  • 1970-01-01
相关资源
最近更新 更多