[英]Why .current and .props are always undefined in my react native ref?
[英]Why is my Ref in React Native not working?
我正在使用 React Native 來構建聊天消息頁面。
我有以下代碼:
import React from 'react'; import {View,ScrollView,Text} from 'react-native'; import {Button} from 'native-base'; export default class MatchContact extends React.Component { constructor(props){ super(props); this.scrollRef = React.createRef(); } state = { messages: ['message1','message2','message3','message4'] } handleScroll(){ this.scrollRef.scrollToEnd() } render(){ return( <View> <Button onPress={()=>this.handleScroll()}> <Text> Scroll To Bottom </Text> </Button> <ScrollView ref={this.scrollRef}> {this.state.messages.map(message => ( <Text> {message} <Text/> ))} </ScrollView> </View> ) }
因此,當我按下“滾動到底部”按鈕時,我希望 ScrollView 滾動到頁面末尾,但出現錯誤:
類型錯誤:_this5.scrollRef.scrollToEnd 不是函數。 (在 '_this5.scrollRef.scrollToEnd()' 中,'_this5.scrollRef.scrollToEnd' 未定義)
嘗試獲取 ref 如下
<ScrollView
keyboardShouldPersistTaps="handled"
ref={(ref) => this.scrollView = ref}>
基本上你有兩個選擇:
選項1:
使用this.scrollRef.current
:
handleScroll(){
this.scrollRef.current.scrollToEnd()
}
或者
選項2:
<ScrollView ref={ref => this.scrollRef = ref}>
....
</ScrollView>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.