liubinis86 / blog

Some experience summary
9 stars 1 forks source link

antd-mobile 的 Carousel 轮播组件踩坑记录 #5

Open liubinis86 opened 5 years ago

liubinis86 commented 5 years ago

问题描述:

解决办法:

  1. 要给 state 中的对应的 data 设置长度不少于2的数组作为默认值。
import { Carousel } from "antd-mobile";
class App extends React.Component {
  state = {
    // **最少长度为2,因为一张图片滚不了**
    data: [1, 2],
    imgHeight: 176
  };
  componentDidMount() {
    // 假装对state.data进行了异步操作
   setTimeout(()=>{this.setState(data:[3,4,5])},100)
  }
  render() {
    return (
      <Carousel autoplay infinite>
        {this.state.data.map(val => (
          <img
            key={val}
            src={`https://www.abc.a${val}.png`}
          />
        ))}
      </Carousel>
    );
  }
}
  1. 在图片异步拉取完成之后再展示轮播图。
import { Carousel } from "antd-mobile";
class App extends React.Component {
  state = {
    data: [],
    imgHeight: 176
  };
 componentDidMount() {
    // 假装对state.data进行了异步操作
   setTimeout(()=>{this.setState(data:[3,4,5])},100)
  }
  render() {
    return (
      // **当数据加载完再展示**
     {this.state.data.length&& <Carousel autoplay infinite>
        {this.state.data.map(val => (
            <img
              src={`https://www.abc.a${val}.png`}
            />
        ))}
      </Carousel>}
    );
  }
}
826587163 commented 4 years ago

谢谢