我如何在React Native中从另一个组件调用函数?

ethans33

我如何从另一个组件调用函数?

App.js

<Button onPress={movePopUpCard()}></Button>
<PopUpCard/>

PopUpCard.js

const movePopUpCard = () => {
   //Code to update popUpCardX
}

<Animated.View style={[
    {transform: [{scale: scale}, {translateX: popUpCardX}]},
    {position: 'absolute'}
]}>
</Animated.View>
Ashwith Saldanha

如果您使用的是功能组件,则必须使用forwardRef添加对该组件的引用,并使用useImperativeHandle来实现要通过引用访问的方法,这里是一个示例,这里我调用了bounce方法,该方法增加了组件的规模,

小吃:https : //snack.expo.io/@ashwith00/adequate-salsa

码:

App.js

export default function App() {
  const boxRef = React.useRef();
  return (
    <View style={styles.container}>
      <AnimatedBox ref={boxRef} />
      <Button title="Bounce" onPress={() => boxRef.current.bounce()} />
    </View>
  );
}

AnimatedBox.js

import React, { forwardRef, useImperativeHandle, useRef } from 'react';
import { View, Animated } from 'react-native';

export default forwardRef((props, ref) => {
  const scale = useRef(new Animated.Value(1)).current;
  useImperativeHandle(
    ref,
    () => ({
      bounce: () => {
        Animated.timing(scale, {
          toValue: 1.5,
          duration: 300,
        }).start(({ finished }) => {
          if (finished) {
            Animated.timing(scale, {
              toValue: 1,
              duration: 300,
            }).start();
          }
        });
      },
    }),
    []
  );
  return (
    <Animated.View
      style={{
        width: 100,
        height: 100,
        backgroundColor: 'red',
        transform: [{scale}]
      }}
    />
  );
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在angular2中调用另一个组件函数

如何从React-Native中的另一个类调用函数?

如何在Angular 2中调用标头组件函数到另一个组件?

一个React组件如何在另一个React组件中调用方法?

如何从React-Native中的另一个函数调用一个函数?

如何在另一个调用this.setState()的函数内部的函数中访问组件的状态?

如何在React Native中从另一个文件调用类的函数?

如何从一个组件调用另一个组件的函数?反应

如何从React组件中的另一个文件调用函数

如何在React组件中的另一个函数中访问useEffect的异步数据

React组件中另一个文件中的React JS调用函数

如何从另一个组件调用mixin函数?

如何在React Native中从另一个功能组件更改一个功能组件的状态?

如何在React Native中导航到类组件中的另一个屏幕

在反应中如何调用另一个组件中的一个组件?

我如何在另一个函数中调用函数?

从React组件函数中的另一个文档调用普通javascript函数

如何在反应中从另一个组件调用函数

如何从另一个组件调用函数

如何从另一个组件中的组件调用函数?

如何在另一个文件中获取组件的状态 react native

我如何在反应中调用另一个函数已经使用的函数

如何在react native中使用另一个类的参数调用函数?

从 React.js 中的另一个类组件调用函数

如何从另一个组件中的组件正确调用函数

在 React Native 中导航时,如何从另一个组件调用函数?

如何使一个组件中的按钮 onClick 调用另一个组件中的函数 React

如何在 React Native 的另一个函数中调用函数

如何从另一个组件调用函数到另一个组件