【问题标题】:Carousel of components in React?React 中的组件轮播?
【发布时间】:2020-06-11 20:54:42
【问题描述】:

我正在使用 React 构建一个网站,对于“新闻”部分,我有一个代表不同新闻的 3 个组件的列表。它们属于一个 flexbox,我试图让它们响应。对于移动设备,我希望只显示 3 个组件中的一个,并且能够单击 2 个箭头来浏览新闻。就像一个普通的图像轮播,但由组件组成。我怎样才能做到这一点? These are the components

我放置所有“新闻”的代码

  render() {
let content = <div>Loading...</div>;
if (!this.state.isLoading) {
  content = (
    <Aux>
      <New
        image={img1}
        title={this.state.news[0].title}
        text={this.state.news[0].text}
        date={this.state.news[0].date}
        classes="new-1"
      />
      <New
        image={img2}
        title={this.state.news[1].title}
        text={this.state.news[1].text}
        date={this.state.news[1].date}
        classes="new-2"
      />
      <New
        image={img3}
        title={this.state.news[2].title}
        text={this.state.news[2].text}
        date={this.state.news[2].date}
      />
    </Aux>
  );
}
return content;

}

这是“新”组件

   const New = props => {
  const imageStyle = {
    backgroundImage: `url(${props.image})`
  };

  return (
    <div className={`new-wrapper ${props.classes}`}>
      <div className="new-image" style={imageStyle}></div>
      <div className="new-content">
        <h4>{props.title}</h4>

        <div className="text-wrapper">
          <p>{props.text}</p>
        </div>

        <div className="date">
          <span>{props.date}</span>
        </div>
      </div>
    </div>
  );
};

【问题讨论】:

  • 你的代码在哪里?如果您添加一个codeandbox示例会更好。
  • @SILENT 我编辑了问题

标签: javascript css reactjs npm react-router


【解决方案1】:

为了达到您想要的结果,我会使用像 https://react-slick.neostack.com/ 这样的轮播插件

您可以将其设置为在桌面上显示三张幻灯片,而在移动设备上只显示一张,这样您就可以让箭头穿过新闻卡片。

我还会使用 map 函数循环数组的每个元素来呈现所有新闻。这样,它将为您的状态或数组中的每个元素动态创建一个新闻卡片。看这个例子How to render an array of objects in React?

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2022-10-19
    • 2016-11-11
    • 1970-01-01
    • 2018-04-18
    • 2021-12-27
    • 2023-03-12
    • 1970-01-01
    • 2022-07-09
    • 1970-01-01
    相关资源
    最近更新 更多