我想使用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.entries
为 null
。
您必须初始化它:
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/