Почему мой Ref в React Native не работает? - PullRequest
0 голосов
/ 26 марта 2020

Я использую 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 прокрутит до конца страницы, но я получил ошибку:

TypeError: _this5.scrollRef.scrollToEnd не является функцией. (В _this5.scrollRef.scrollToEnd () ', _this5.scrollRef.scrollToEnd' не определено)

Ответы [ 2 ]

0 голосов
/ 26 марта 2020

В основном у вас есть два варианта:

Опция 1:

использование this.scrollRef.current:

handleScroll(){
  this.scrollRef.current.scrollToEnd()
}

или

Опция 2:

<ScrollView ref={ref => this.scrollRef = ref}>
....
</ScrollView>
0 голосов
/ 26 марта 2020

Попробуйте получить ссылку ниже:

<ScrollView  
keyboardShouldPersistTaps="handled"
ref={(ref) => this.scrollView = ref}>
...