使用 React 在 Carousel 中渲染组件

Rendering Component in Carousel using React

我想实现 Materialize 这样的轮播。 从我获取数据的地方有一个 API,所以根据 Materialize

我比较了控制台或 Materialise 默认值和我渲染的组件。

我想问题是,它没有继承 carousel-item

的属性

Class carousel-item 应该在 Class carousel.

内部渲染
<div className="carousel">
// These are supposed to be dynamic, below component is not present here
  <div className="carousel-item">
  </div>
</div>

我试图以这种方式呈现数据。

    renderAlbums(){
      return this.state.albums.map(album =>
          <Card song={album.name} singer={album.artist_name} src={album.cover_photo_url}/>
      );
    }

渲染数据<Card />(它包含carousel-item的class),应该放置包含carousel-item的class的卡片。

class Carousel extends Component {
    state = { albums: [] };
    componentWillMount() {
      axios.get('https://cors-anywhere.herokuapp.com/https://stg-resque.hakuapp.com/albums.json')
        .then(response => this.setState({albums: response.data}));
    }
    renderAlbums(){
      return this.state.albums.map(album =>
          <div className="carousel-item"><Card key={album.name} song={album.name} singer={album.artist_name} src={album.cover_photo_url}/></div>
      );
    }
  render() {
    return (
        <div className="carousel center">
          {this.renderAlbums()}
        </div>
    );
  }
}

export default Carousel;

这是我的卡片组件

class Card extends Component {
  render() {
    return (

        <div className="card z-depth-4">
          <div>
            <img src={this.props.src} />
          </div>
          <p>{this.props.song}</p>

          <div className="singer">{this.props.singer}</div>
        </div>
    );
  }
}
export default Card;

编辑:

但它没有按预期方式工作。 请建议我,我做错了什么?

首先,您的 Carousel 中没有任何内容说明哪个元素处于活动状态。您需要有一个指向活动元素的状态变量。

那么你只需要绘制 [-2, -1, 0, 1, 2] 偏移量与活动偏移量。并且每张渲染的卡片都需要知道哪个偏移量才能知道它们的样式。

axios.get 中,我看到您正在使用代理 link。

一个原因是,它可能会产生问题。


其他原因可能是您试图将 carousel-item 放入 carousel。 尝试将 center class 添加到 carouselcarousel-item.

检查这些是否有效。