无法使用 react-native-snap-carousel

Can't use 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 Native

我看到一个问题(和我一样) 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' },
]

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