Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
React native 如何在React Native中将函数传递给其他组件?_React Native - Fatal编程技术网

React native 如何在React Native中将函数传递给其他组件?

React native 如何在React Native中将函数传递给其他组件?,react-native,React Native,我有以下小吃: js导入StepOne、StepII、StepIII、StepFour和MyScrollView。在本文中,我想让组件StepOne、StepII、StepIII和StepFour可以访问MyScrollView中的moveToPage函数如何实现这一点?我尝试过使用道具(遵循各种React教程),但没有成功。使用道具是实现这一目标的最佳方法吗?这种方法是否存在缺陷?谢谢如果第二个组件是第一个组件的子组件,您可以通过道具传递任何东西 _myFunction(val){} //d

我有以下小吃:


js导入StepOne、StepII、StepIII、StepFour和MyScrollView。在本文中,我想让组件StepOne、StepII、StepIII和StepFour可以访问MyScrollView中的moveToPage函数如何实现这一点?我尝试过使用道具(遵循各种React教程),但没有成功。使用道具是实现这一目标的最佳方法吗?这种方法是否存在缺陷?谢谢

如果第二个组件是第一个组件的子组件,您可以通过道具传递任何东西

_myFunction(val){} //do something
render(){
        return(
                <Second ABC={(val)=> this._myFunction(val) } /> //here the props name is ABC
        )
 }

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

如果将以下内容添加到
MyScrollView
组件中,这将允许您将引用作为prop
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>
{this.scrollView=ref}}>
this.scrollView.moveToPage(2)}/>//您可能希望添加一个保护,以确保this.scrollView不为null。
您可以在这个更新的小吃中看到它的工作原理


谢谢你的帮助,效果很好。我还想把同样的函数传递给孩子的孩子。我还有另一个小吃:你能不能指导我如何将同样的功能提供给SliderEntry.js。当前,当图像转盘出现,然后单击图像时,访问moveToPage时出现错误。谢谢
<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>