reactjs - 无法使用react-native-snap-carousel

标签 reactjs react-native carousel react-native-snap-carousel

我想使用react-native-snap-carousel,但是当我尝试初始化时出现错误:(

示例:

import Carousel from 'react-native-snap-carousel';

export class MyCarousel extends Component {

_renderItem ({item, index}) {
    return (
        <View style={styles.slide}>
            <Text style={styles.title}>{ item.title }</Text>
        </View>
    );
}

render () {
    return (
        <Carousel
          ref={(c) => { this._carousel = c; }}
          data={this.state.entries}
          renderItem={this._renderItem}
          sliderWidth={sliderWidth}
          itemWidth={itemWidth}
        />
    );
}}

我的代码:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Carousel from 'react-native-snap-carousel';

export default class App extends React.Component {
 _renderItem ({item, index}) {
   return (
      <View style={styles.slide}>
          <Text style={styles.title}>{ item.title }</Text>
      </View>
);}
 render () {
   return (
    <Carousel
      ref={(c) => { this._carousel = c; }}
      data={this.state.entries}
      renderItem={this._renderItem}
      sliderWidth={150}
      itemWidth={100}
    />
); 
}} 
    const styles = StyleSheet.create({
     container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
   }});

Screenshot app.js 上的 react 相同

我发现一个问题(和我一样) link to Github Issue

但没有回答,问题很接近

最佳答案

如屏幕截图所示,this.state.entriesnull

您必须初始化它:

export default class App extends React.Component {
  constructor() {
    super()
    this.state = {
      entries: [],
    }
  }
  _renderItem ({item, index}) {
    return (
      <View style={styles.slide}>
          <Text style={styles.title}>{ item.title }</Text>
      </View>
  );}

  render () {
    return (
      <Carousel
        ref={(c) => { this._carousel = c; }}
        data={this.state.entries}
        renderItem={this._renderItem}
        sliderWidth={150}
        itemWidth={100}
      />
 ); 
}}

在此示例中,entries: [] 不会显示任何内容,因为其中没有对象。您可以用想要的数据初始化它:

entries: [
  { title: 'hello' },
  { title: 'world' },
]

顺便说一句,这个问题与插件本身无关,即使他们可以捕获它。

关于reactjs - 无法使用react-native-snap-carousel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51944706/

相关文章:

javascript - React Native Flex-Wrap 不会换行或将文本挤压到屏幕一侧

css - Bootstrap 轮播元素卡入到位并更改父 div 的高度

jar - 将 .jar 文件添加到 React native

react-native - react 原生 mobx 值不是原始值

css - 对齐 Bootstrap 轮播控制中间垂直

css - 更改轮播背景的亮度( Bootstrap )

javascript - 类型错误 : Cannot read property 'tap' of undefined when adding webpack-subresource-integrity

javascript - 在添加复选框事件的 react 中未定义“this”

javascript - 如何使用react js将html表单提交的信息显示到另一个页面上?

javascript - 检测包含 http 请求的 forEach 循环结束?