React Native - добавление поля: 1 в Camera Roll - PullRequest
0 голосов
/ 10 июля 2019

Как добавить margin: 1 отлично в моем Camera Roll?Потому что, когда я добавляю margin: 1 в мой <Image .../>, порядок не будет в правильном порядке.

Результат, который я хочу, похож на результат в Instagram.Там нет поля слева и справа, верно?

Так же, как это изображение:

enter image description here

Вот мои коды:

render() {
return(
  <View style={styles.container}>
    {/* <SelectedImage source={{uri: this.state.pickedImage}}/> */}
    <Image source={{uri: this.state.pickedImage}} style={styles.image}/>
    <ScrollView contentContainerStyle={styles.scrollView} showsVerticalScrollIndicator={false}>
      {this.state.photos.map((photos, index) => {
        return(
          <TouchableHighlight 
            style={{opacity: index === this.state.index ? .5 : 1}}
            onPress={() => this.setState({pickedImage: photos.node.image.uri})}
            key={index}
            underlayColor='transparent'
          >
            <Image
              style={{width: width / 3, height: width /3}}
              source={{uri: photos.node.image.uri}}
              resizeMode='cover'
            />
          </TouchableHighlight>
        );
      })}
    </ScrollView>
  </View>
); 
}
}

const styles = StyleSheet.create({
container: {
 height: '100%',
 width: '100%',
 justifyContent: 'center',
 alignItems: 'center',
 backgroundColor: 'white'
},
scrollView: {
 flexWrap: 'wrap',
 flexDirection: 'row'
},
scrollViewContainer: {
 flex: 1,
 flexDirection: 'row',
},
 image: {
 width: '100%',
 height: 300,
 backgroundColor: 'black'
}
});

Это мой собственный результат: (Не беспокойтесь о черной границе, я просто не обрезал идеально, и у меня есть только 6 фотографий в моем эмуляторе Android).

enter image description here

Ответ Предложено:

componentDidMount() {
this.getPhotos();
this.rightButtonIcon();
requestExternalStoragePermission();

photoFilter = () => {
  var arr = this.state.photos;
  var number = 0;
  arr.forEach((item) => {
    switch(number) {
      case 0: 
        number = 1;
        item.position="left"
      break;
      case 1:
        number = 2;
        item.position="center"
      break;
      case 2: 
        number = 0;
        item.position="right"
      break;
      default:
        return null;
    }
  })
  this.setState({photos: arr})
}
};

 imageStylePositionCalc = (pos) =>{
  if(pos==="left") return {marginRight:1,marginBottom:1}
  if(pos==="center") return {marginRight:1,marginBottom:1}
  if(pos==="right") return {marginBottom:1}
 }

  render() {
return(
  <View style={styles.container}>
    {/* <SelectedImage source={{uri: this.state.pickedImage}}/> */}
    <Image source={{uri: this.state.pickedImage}} style={styles.image}/>
    <ScrollView contentContainerStyle={styles.scrollView} showsVerticalScrollIndicator={false}>
      {this.state.photos.map((photos, index) => {
        return(
          <TouchableHighlight 
            style={{opacity: index === this.state.index ? .5 : 1}}
            onPress={() => this.setState({pickedImage: photos.node.image.uri})}
            key={index}
            underlayColor='transparent'
          >
            <Image
              style={[{width: width / 3, height: width /3}, this.imageStylePositionCalc(photos.position)]}
              source={{uri: photos.node.image.uri}}
              resizeMode='cover'
            />
          </TouchableHighlight>
        );
      })}
    </ScrollView>
  </View>
); 
}
}

Это еще одна проблема, поле: 1 занимает всю ширину экрана, и поля нетво 2-м ряду:

enter image description here

Ответы [ 2 ]

1 голос
/ 11 июля 2019

Перед тем, как приступить к работе с картой, я бы посоветовал пройтись по каждой части массива и добавить значение, которое говорит, будет ли оно размещено справа, слева или по центру. Что-то вроде:

photoFilter=()=>{
   var arr=this.state.photos;
   var number=0;
   arr.forEach((item)=>{
      switch (number){
         case 0: 
            number=1;
            item.position="left"
            break;  
         case 1: 
            number=2;
            item.position="center"
            break;  
         case 2: 
            number=0;
            item.position="right"
            break; 
         default:
            return null 
      }
  })
this.setState({photos:arr})
}

затем при рендеринге изображения:

<Image
style={[{width: width / 3, height: width /3},this.imageStylePositionCalc(item.position)]}
source={{ uri: photos.node.image.uri }}
resizeMode="cover"
/>

затем добавьте функцию:

imageStylePositionCalc=(pos)=>{
  if(pos==="left") return {marginRight:1,marginBottom:1}
  if(pos==="center") return {marginRight:1,marginBottom:1}
  if(pos==="right") return {marginBottom:1}
}

Возможно, это не лучший ответ, но он должен работать

UPDATE: Проблема в том, что вы определяете функцию photoFilter внутри didMount.

Что я имел в виду, когда сказал, что вызывать его внутри componentDidMount было:

componentDidMount() {
this.getPhotos();
this.rightButtonIcon();
requestExternalStoragePermission();
this.photoFilter
}

photoFilter = () => {
      var arr = this.state.photos;
      var number = 0;
      arr.forEach((item) => {
        switch(number) {
          case 0: 
            number = 1;
            item.position="left"
          break;
          case 1:
            number = 2;
            item.position="center"
          break;
          case 2: 
            number = 0;
            item.position="right"
          break;
          default:
            return null;
        }
      })
      this.setState({photos: arr})
    }
0 голосов
/ 11 июля 2019

У меня есть решение вашей проблемы, которое может быть не самым лучшим, потому что я не знаю, как избавиться от верхнего и нижнего краев, но как угодно.

const styles = StyleSheet.create({
    container: {
        height: '100%',
        width: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'white'
    },
    scrollView: {
        flexWrap: 'wrap',
        flexDirection: 'row',
        justifyContent: 'space-between', // This one is new
        marginHorizontal: -3 // This one is new
    },
    scrollViewContainer: {
        flex: 1,
        flexDirection: 'row'
    },
    image: {
        width: '100%',
        height: 300,
        backgroundColor: 'black'
    }
});

/* Rest of the code stays the same, only the image style gets changed to the follwoing */

<Image
    style={{
        width: width / 3,
        height: width / 3,
        margin: 1
    }}
    source={{ uri: photos.node.image.uri }}
    resizeMode="cover"
/>

Надеюсь, это поможет.

...