1.安装:

npm i autoresponsive-react --save

 2.使用:

官方示例:github:https://github.com/xudafeng/autoresponsive_react_native_sample

 

引用:

let AutoResponsive = require("autoresponsive-react-native");

 

主体:

render() {
    return (
      <ScrollView style={styles.container}>
        <AutoResponsive {...this.getAutoResponsiveProps()}>
          {this.renderChildren()}
        </AutoResponsive>
      </ScrollView>
    );
  }

 方法:

getAutoResponsiveProps() {
    return {
      itemMargin: 0
    };
  }

 

renderChildren() {
    return this.state.array.map((i, key) => {
      return (
        <View style={this.getChildrenStyle(i)} key={key}>
          <TouchableOpacity
            onPress={() =>{}}
          >
            <Image
              style={this.getChildrenStyle(i)}
              source={i}
            />
          </TouchableOpacity>
        </View>
      );
    }, this);
  }

 这个方法显示item内容,下面详细分析.

 

3.显示图片:

数据源:

const image_1 = require("../../img/lookbook_images/1.png");
const image_2 = require("../../img/lookbook_images/2.png");
const image_3 = require("../../img/lookbook_images/3.png");
const image_4 = require("../../img/lookbook_images/4.png");
const image_5 = require("../../img/lookbook_images/5.png");
const image_kc1 = require("../../img/lookbook_images/kc1.png");
const image_kc2 = require("../../img/lookbook_images/kc2.png");
const image_kc3 = require("../../img/lookbook_images/kc3.png");
const image_kc4 = require("../../img/lookbook_images/kc4.png");
const image_kc5 = require("../../img/lookbook_images/kc5.png");

state = {
    array: [
   image_1,image_3,image_2,image_4,image_5,image_kc1,image_kc2,image_kc3,image_kc4,image_kc5]
    };

 在renderChildren()里面遍历出来.

getChildrenStyle(i) {
    let imageWidth = resolveAssetSource(i).width;
    let imageHeight = resolveAssetSource(i).height;

    return {
      width: SCREEN_WIDTH / 2,
      height: (imageHeight / imageWidth) * (SCREEN_WIDTH / 2),
    };
  }

 然后这个方法控制item的style,必须要给予View宽高,否则AutoResponsive会计算不了宽高而报错.

但是只是给View宽高是不够的,因为如果图片尺寸太大,会显示不全.这时候只要View和Image统一一个尺寸就可以了.(高度通过等比计算缩小)

 

这是显示效果:

 


 

 

 

 

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐