【问题标题】:Can you use React Native RefreshControl without hooks?你可以在没有钩子的情况下使用 React Native RefreshControl 吗?
【发布时间】:2020-09-06 08:35:05
【问题描述】:

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

【问题讨论】:

    标签: reactjs react-native react-hooks pull-to-refresh uirefreshcontrol


    【解决方案1】:

    您可以在基于类的组件中使用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;
    

    【讨论】:

      猜你喜欢
      • 2012-02-08
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      • 2021-01-22
      • 2020-03-22
      • 2011-12-15
      相关资源
      最近更新 更多