reactjs - 你可以在没有钩子的情况下使用 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;
推荐阅读
- hyperledger-fabric - 我想构建一个 Hyperledger Fabric 网络,在多个组织的多个主机上运行
- java - 如何将临时授予的 ContentProvider 权限传递给 Service?
- c# - 登录网站并使用 Html Agility Pack 设置用户代理
- swift - 如何使用枚举创建计算函数?
- docker - Dockerfile 的第一行 - 什么操作系统?
- authorization - 为动态角色和属性建模 XACML 策略
- kubernetes - Traefik 入口不适用于集群 IP
- ionic-framework - 如何将我的 Ionic 4 应用程序升级到最新的 Ionic 版本?
- css - 如何使用来自其父级的 ::after 的通用兄弟选择器
- r - 使用 NA 删除行和列但保留 R 中的值