首页 > 解决方案 > 如何将函数传递给 React Native 中的其他组件?

问题描述

我有以下零食: https ://snack.expo.io/@sj458147/rewrite39

App.js 导入 StepOne、StepTwo、StepThree、StepFour 和 MyScrollView。在此我想让 MyScrollView 中的函数 moveToPage 可供 StepOne、StepTwo、StepThree 和 StepFour 组件访问,我该如何实现?我曾尝试使用道具(遵循各种 React 教程)但没有成功。使用道具是实现这一目标的最佳方式,这种方法有什么陷阱吗?谢谢

标签: react-native

解决方案


您遇到的问题是您没有获得对实例的引用,MyScrollView因此您无法访问其中的函数

如果您将以下内容添加到您的MyScrollView组件中,这将允许您将引用作为道具传回onRef

componentDidMount () {
  // this creates the reference when the component mounts
  if (this.props.onRef) {
    this.props.onRef(this);
  }
}

componentWillUnmount () {
  // this removes the reference when the component unmounts 
  if (this.props.onRef) {
    this.props.onRef(undefined);
  }
}

然后,您可以onRef按如下方式使用道具

<MyScrollView
  onRef={ref => {this.scrollView = ref}}>
  <StepOne next={()=> this.scrollView.moveToPage(2)}/> // you may wish to add a protection to make sure that this.scrollView is not null.
  <StepTwo />
  <StepThree />
  <StepFour />
</MyScrollView>

你可以在这个更新的小吃中看到它的工作原理

https://snack.expo.io/@andypandy/creating-onref-prop-for-custom-scrollview


推荐阅读