你可以在没有钩子的情况下使用 React Native RefreshControl 吗?



我想在我的 React Native 应用程序中使用 RefreshControl,但他们文档中的演示实现使用了钩子,我没有在我的应用程序中使用钩子。当我复制粘贴演示代码时,我收到错误Hooks can only be called inside of the body of a function component.有没有办法让我在不将组件转换为函数组件的情况下使用此库?

您可以在基于类的组件中使用RefreshControl,从而避免钩子。下面是一个示例:

import React, { Component } from 'react';
import { StyleSheet, View, ListView, RefreshControl, Text } from 'react-native'

class RefreshControlExample extends Component {
constructor () {
super()
this.state = {
refreshing: false,
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2 }),
cars : [
{name:'BMW',color:'White'},
{name:'Mercedes',color:'Green'}
]
}
}
componentWillMount(){
this.setState({ dataSource:
this.state.dataSource.cloneWithRows(this.state.cars) })
}
render() {
return (
<View style={{flex:1}}>
<ListView
refreshControl={this._refreshControl()}
dataSource={this.state.dataSource}
renderRow={(car) => this._renderListView(car)}>
</ListView>
</View>
)
}
_renderListView(car){
return(
<View style={styles.listView}>
<Text>{car.name}</Text>
<Text>{car.color}</Text>
</View>
)
}
_refreshControl(){
return (
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={()=>this._refreshListView()} />
)
}
_refreshListView(){
//Start Rendering Spinner
this.setState({refreshing:true})
this.state.cars.push(
{name:'Fusion',color:'Black'},
{name:'Yaris',color:'Blue'}
)
//Updating the dataSource with new data
this.setState({ dataSource:
this.state.dataSource.cloneWithRows(this.state.cars) })
this.setState({refreshing:false}) //Stop Rendering Spinner
}
}
const styles = StyleSheet.create({
listView: {
flex: 1,
backgroundColor:'#fff',
marginTop:10,
marginRight:10,
marginLeft:10,
padding:10,
borderWidth:.5,
borderColor:'#dddddd',
height:70
}
})
export default RefreshControlExample;

最新更新