javascript - react : How to pass an array as props and render a list of images?

标签 javascript reactjs typescript frontend

我是新来的 react 。我想循环图像列表(Json)并在屏幕上显示这些图像。所以我想用 Array 创建一个 prop。但我不知道如何将数组作为 Prop 传递?你能帮忙看一下吗?

var images = [
  "./resources/bgdefault.jpg",
  "./resources/bg1.jpg",
  "./resources/bg2.jpg",
  "./resources/bg3.jpg",
  "./resources/bg4.jpg",
  "./resources/bg5.jpg",
  "./resources/bg6.jpg",
  "./resources/bg7.jpg",
  "./resources/bg8.jpg"
];

type State = {
  index: number;
};

type Props = {
  backgroundDuration: number;
  imagePath: Array<string>;
};

export class BackgroundImage extends React.Component<Props, State> {
  timerID: number;

  constructor(props: Props) {
    super(props);
    this.state = {
      index: -1
    };
    this.timerID=0;
  }

.....

  render() {
    const path:string = images[this.state.index];
    return (
      <div
        style={{
          width: "100%",
          height: "100%",
          backgroundSize: "cover",
          backgroundImage: `url(${path})`
        }}
      ></div>
    );
  }
}

最佳答案

您可以将任何 JavaScript 变量传递给 prop。例如,如果您想循环遍历 URL 的数组,并为每个 URL 呈现一个 img 标记:

// ImageList.js file

function ImageList (props) {
  const { images } = props

  return <div>{ images.map(imgUrl => <img src={imgUrl} />) }</div>
}

在父组件中你会有类似的内容:

// App.js file

import ImageList from './ImageList'

function App () {
  const images = [
    "./resources/bgdefault.jpg",
    "./resources/bg1.jpg",
    "./resources/bg2.jpg",
    "./resources/bg3.jpg",
    "./resources/bg4.jpg",
    "./resources/bg5.jpg",
    "./resources/bg6.jpg",
    "./resources/bg7.jpg",
    "./resources/bg8.jpg"
  ]

  return <ImageList images={images} />
}

此示例使用 function 组件,但 props 和 JSX 与 class 组件的工作方式相同(只需使用 this.props 而不是 Prop )。

关于javascript - react : How to pass an array as props and render a list of images?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60877944/

相关文章:

javascript - 联合类型的部分键作为 typescript 中对象的键

javascript - 绘图软刷

javascript - 了解 React-Redux 和 mapStateToProps()

node.js - Azure 服务器上的 GraphQL

reactjs - 服务器渲染的 React ExpressJS 前端泄露用户的 Redux 存储数据

javascript - 从刷新的 JSON 更新 img src

javascript - Sequelize 查找或创建项目列表

javascript - 如何在 Vue.js 中传递动态页面 :id to $http. 获取 url

javascript - AngularJS 将子状态参数插入 $urlRouterProvider (UI-Router)

javascript - 如何获取已注册的自定义元素列表