react-native - 如何将函数传递给 React Native 中的其他组件?
问题描述
我有以下零食: https ://snack.expo.io/@sj458147/rewrite39
App.js 导入 StepOne、StepTwo、StepThree、StepFour 和 MyScrollView。在此我想让 MyScrollView 中的函数 moveToPage 可供 StepOne、StepTwo、StepThree 和 StepFour 组件访问,我该如何实现?我曾尝试使用道具(遵循各种 React 教程)但没有成功。使用道具是实现这一目标的最佳方式,这种方法有什么陷阱吗?谢谢
解决方案
您遇到的问题是您没有获得对实例的引用,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
推荐阅读
- reactjs - ReasonReact useState 与获取的数据
- r - 根据另一列中的条件过滤重复项
- javascript - 如何延迟使用 Javascript 制作的警报框?
- python - 如何将索引的名称更改为熊猫中的其他值
- python - 如何解决“运行 SQL 查询时出错”。蟒蛇中的错误
- r - R Shiny 服务器变量定义。修改后的值不反映
- objective-c - 应用所选图像时 UITabBarButton 索引发生变化
- java - 无法在docker中将springboot连接到mysql
- javascript - 从javascript中的嵌套数组中过滤数组
- azure - 更改运行 Azure 容器实例的端口