2017-10-04 28 views
3

我試圖添加一個ref到React Native中的一個功能組件,以便在FlatList組件上使用scrollToEnd。如何使用重組的toClass HOC添加一個功能組件的ref?

我想使用repose這個和作爲他們的文檔狀態,toClass()應該能夠處理這個。但是,沒有給出任何示例。

目前,這是我的失敗實現。有人能告訴我我做錯了什麼嗎?

我會非常感激!

import React from 'react'; 
import PropTypes from 'prop-types'; 
import { FlatList, View, Text } from 'react-native'; 
import { graphql } from 'react-apollo'; 
import { compose, toClass, lifecycle } from 'recompose'; 

import CommentItem from './CommentItem'; 
import { commentsQuery } from '../../queries/comments'; 

const CommentScreen = ({ onRef, currentUser, data: { comments, loading } }) => { 
    if (loading) { 
    return (
     <View> 
     <Text>Loading...</Text> 
     </View> 
    ); 
    } 

    return (
    <FlatList 
     ref={ref => { 
     this.refs.commentList = ref; 
     }} 
     data={comments} 
     keyExtractor={item => item.id} 
     renderItem={({ item }) => <CommentItem {...item} currentUser={currentUser} />} 
    /> 
); 
}; 

export default compose(
    toClass, 
    graphql(commentsQuery), 
    lifecycle({ 
    componentDidMount() { 
     console.log('PROPZZZ', this.commentList); 
    }, 
    }), 
)(CommentScreen); 

CommentScreen.propTypes = { 
    fetchComments: PropTypes.func.isRequired, 
    updateId: PropTypes.number.isRequired, 
    comments: PropTypes.arrayOf(Object), 
    text: PropTypes.string.isRequired, 
}; 

回答

0

您必須在生命週期方法中從this.refs訪問您的元素。

lifecycle({ 
    componentDidMount() { 
    console.log('PROPZZZ', this.refs.commentList); 
    //       ^^^^ 
    } 
}) 

你可以看到它在這裏工作: https://snack.expo.io/Sy-rCBQhW

0

只需使用一類部件,而不是一個功能組件,如果你需要使用ref。但是,如果由於某些原因需要使用功能組件,則可以使用withHandlers。請參閱this SO question的答案以瞭解如何使用它。

+0

我試過這個答案之前,我訴諸我的實施,因爲它沒有工作。但是,我可能只是使用一個類組件。 –

+0

@ReinVanImschoot你介意分享你的代碼嗎? – wuct

相關問題