如何在反应本机按钮的 onPress 上滚动底部?

kal*_*kar 1 button scrollview react-native onpress

我已在简单屏幕上添加了按钮,每当按下按钮时我想滚动底部。向按钮 onPress 添加什么代码?

render() {
 return (
  <ScrollView>
   {this.yourComponents()}
   <Button>Scroll To Bottom </Button>
  </ScrollView>
  )
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 7

你可以使用 来做到这一点ref

render() {
 return (
  <ScrollView ref={scrollView => this.scrollView = scrollView}>
   {this.yourComponents()}
   <Button onPress={() => {this.scrollView.scrollToEnd()}}>Scroll To Bottom </Button>
  </ScrollView>
  )
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用useRef钩子来完成此操作。

const scrollView = useRef();
Run Code Online (Sandbox Code Playgroud)
const scrollView = useRef();

const onPress = () => {
  scrollView.current.scrollToEnd();
}

<Button onPress={onPress} /> 
Run Code Online (Sandbox Code Playgroud)