我如何从另一个组件调用函数?
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>
如果您使用的是功能组件,则必须使用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] 删除。
我来说两句