[英]How to animate width of native-react component?
我正在使用 Animated API import { Animated } from 'react-native'
在 style 中指定width: animated-value
時, width
實際上只渲染一次,不會動態變化。 如果您使元素重新渲染,您只能看到幕后的動畫值正在發生變化。
// since only function components can use hooks, wrap the classical component in a function one
// that sets up the hook for it
function withAnimationHook(Component) {
return function WrappedComponent(props) {
const anim = useRef(new Animated.Value(0));
useEffect(() => {
Animated.loop(
Animated.sequence([
Animated.timing(anim.current, {
toValue: 1,
duration: 2000,
}),
Animated.timing(anim.current, {
toValue: 0,
duration: 2000,
}),
])
).start();
}, []);
return <Component {...props} anim={anim} />;
}
}
class AnimatedButton extends React.Component {
render() {
const { anim, width } = this.props
return (
<Animated.View style={{ width: width * anim.current._value }}>
</Animated.View>
)
}
}
export default withAnimationHook(AnimatedButton)
我知道設置動畫值是有效的,因為style={{ transform: [{ scale: anim.current }] }}
效果很好(它會反復增長和縮小)。
為什么width: width * anim.current._value
不為寬度設置動畫?
如何為寬度設置動畫?
this.props.width
只是一個數字,例如64
讓我們試試這個。
const SubView = ({ parentValue = 0, propWidth=2000 }) => {
const animatedValue = useRef(new Animated.Value(0)).current
useEffect(() => {
Animated.timing(animatedValue, {
toValue: parentvalue,
duration: 2000,
}).start()
}, [parentValue])
return (
<Animated.View
style={[
styles.viewStyle,
{
width: animatedValue.interpolate({
inputRange: [0, 1],
outputRange: [0, propWidth],
}),
},
]}
></Animated.View>
)
}
export default React.memo(SubView)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.