【问题标题】:Can't use react-native-snap-carousel不能使用 react-native-snap-carousel
【发布时间】:2019-01-27 09:46:48
【问题描述】:

我想使用 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

但不回答和问题接近

【问题讨论】:

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


    【解决方案1】:

    如截图所示,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' },
    ]
    

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

    【讨论】:

    • 非常感谢@poptocrack :)
    猜你喜欢
    • 2020-03-18
    • 2020-02-05
    • 2020-01-07
    • 1970-01-01
    • 2020-09-03
    • 2020-10-20
    • 2018-02-13
    • 2021-01-22
    • 2021-08-17
    相关资源
    最近更新 更多