javascript - 在轮播中调整图像大小

标签 javascript react-native

我使用“react-native-snap-carousel”,但对于宽图像,它会剪切图像(我看到 50%)。我没有在文档中找到重新调整它们的 Prop 。

如何调整它们的大小以查看 100% 的宽度?

这是我的代码:

renderItem({ item, index }, contactId) {
    const {
        viewportWidth,
    } = this.state;
    const sourceURL = buildVisitCardUrl(contactId, item);
    return (
        <View
        style={{ width: viewportWidth }}
        key={index}
        >
        <Image
        style={{ width: '100%', height: this.hp(75) }}
        source={{ uri: sourceURL }}
        />
        </View>
    );
}

render() {
    <Modal
    animationType="slide"
    visible={open}
    onRequestClose={() => openModal(false, 'listCards')}
    >
        <View style={{ display: 'flex', alignItems: 'center' }}>
            <View>
            <Carousel
            layout="default"
            ref={(c) => { this.carousel = c; }}
            data={listVCard}
            renderItem={({ item, index }) => this.renderItem({ item, index }, contactId)}
            sliderWidth={viewportWidth} // Dimensions.get('window').width
            sliderHeight={viewportHeight} // Dimensions.get('window').height
            itemWidth={this.wp(95)} // 95% of viewportWidth
            contentContainerCustomStyle={{ display: 'flex', alignItems: 'center' }}
            vertical={false}
            />
            </View>
        </View>
    </Modal>
}

最佳答案

我在使用 react-native-snap-carousel 时遇到了同样的问题,并且我找到了使用 React native Dimensions 来解决它的首选方法 Snap carousel Tips and tricks文档。使用此方法,您可以根据设备屏幕尺寸将 slider 设置为 100%。

第一步

为您的项目添加 React Dimensions

import { Dimensions } from 'react-native';

第 2 步

将视口(viewport)宽度定义为常量

const { width: viewportWidth } = Dimensions.get('window');

第 3 步

添加 Carousel 组件属性 sliderWidthitemWidth 作为常量定义如下

<Carousel
     ref={(c) => { this._carousel = c; }}
     data={listVCard}
     renderItem={({ item, index }) => this.renderItem({ item, index }, contactId)}
     sliderWidth={viewportWidth}
     itemWidth={viewportWidth}
 />

关于javascript - 在轮播中调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55048596/

相关文章:

javascript - 从函数返回多个值

javascript - 在react-native功能组件中哪里实现初始化代码

react-native - React Navigation V5 + Redux Saga : How can I navigate from the Saga?

javascript - 是否可以将文件附加到 JavaScript 中的电子邮件?

php - JavaScript 和 PHP 问题

javascript - .htaccess:FilterProvider问题

javascript - 无法在条件检查时设置 .css() 方法

react-native - 获取错误不变违反 : Tried to register two views with the same name

javascript - React Native ListView 数据源始终为 null

javascript - 每隔 X 个位置和 "attempted to assign to readonly property"在数组中插入一个项目