填充对象数组

时间:2019-06-08 13:22:00

标签: reactjs typescript

我有一个对象数组

var photos: Photos[] = [];

照片[]具有以下格式

interface Photos {
  src: string;
  width: number;
  height: number;
}

我有一个接受字符串数组的组件

export type PhotosArray = {
  src: string[]
}

class A extends React.Component<PhotosArray> {

  render() {
    const { src } = this.props;
    return (
    )
};

如何用src数组填充对象数组?

该组件的调用方式如下

<A src={["first", "second", "third", "fourth"]} />

我想确保我的照片[数组]由对象组成,每个对象都有一个src字段,宽度,高度,当src数组进入组件时,我希望该数组填充我对象的字段,也就是说,我想证明它的相似性结构

[
  {
    src: 'first',
    width = some val,
    height = some val
  },
  {
    src: 'second',
    width = some val,
    height = some val
  },
  {
    src: 'third',
    width = some val,
    height = some val
  },
  {
    src: 'fourth',
    width = some val,
    height = some val
  }
]

1 个答案:

答案 0 :(得分:0)

基于道具修改状态被认为是有害的,不赞成使用componentWillRecieveProps的生命周期方法来删除它。

您的替代方法是拉起状态并完全控制A

class Parent extends Component {

/* function that gets srcs */
getSrc() {
 const src = /* from somewhere */
 const photos = this.state.photos
 for (let i = 0; i < srcs.length; i++)
    photos[i].src = srcs[i]

 this.setState({ photos: [ ...photos ] })
}

render() {
    return (<A photos={this.state.photos} />)
  }
}
相关问题