gpt4 book ai didi

reactjs - 如何为一组组件创建一个动态的 React 钩子(Hook)数组

转载 作者:行者123 更新时间:2023-12-04 01:02:59 25 4
gpt4 key购买 nike

const AnimatedText = Animated.createAnimatedComponent(Text);

function Component({ texts }) {
const [visitIndex, setVisitIndex] = React.useState(0);

// can't create an array of shared value for each text
// since useSharedValue is a hook, and that throws a warning
const textScalesShared = texts.map((_) => useSharedValue(1));

// can't create an array of animated style for each text
// since useAnimatedStyle is a hook, and that throws a warning
const animatedTextStyle = textScalesShared.map((shared) =>
useAnimatedStyle(() => ({
transform: [{ scale: shared.value }],
}))
);

useEffect(() => {
// code to reduce text scale one after another
// it will loop over the array of textScaleShared values
// passed to each component and update it
if (visitIndex === texts.length) {
return;
}

textScalesShared[visitIndex].value = withDelay(
1000,
withTiming(0.5, {
duration: 1000,
})
);

const timerId = setTimeout(() => {
setVisitIndex((idx) => idx + 1);
}, 1000);

return () => {
clearTimeout(timerId);
};
}, [visitIndex]);

return texts.map((text, index) => {
if (index <= visitIndex) {
return (
<AnimatedRevealingText
key={index}
fontSize={fontSize}
revealDuration={revealDuration}
style={animatedStylesShared[index]}
{...props}
>
{text}
</AnimatedRevealingText>
);
} else {
return null;
}
});
}

我想将动画样式应用于组件数组,但由于 useSharedValueuseAnimatedStyle都是钩子(Hook),我无法遍历 Prop 并为每个组件创建共享值和相应的样式。
我怎样才能达到同样的效果?
编辑:更新以添加完整代码。

最佳答案

您可以创建一个组件来处理 useSharedValueuseAnimatedStyle 使用 visitIndex 对每个项目进行 Hook 值(value):
AnimatedTextItem.js

const AnimatedText = Animated.createAnimatedComponent(Text);

const AnimatedTextItem = ({text, visited}) => {
const textScaleShared = useSharedValue(1);
const style = useAnimatedStyle(() => ({
transform: [{ textScaleShared.value }],
}));

useEffect(()=> {
if(visited) {
textScaleShared.value = withDelay(
1000,
withTiming(0.5, {
duration: 1000,
});
);
}
}, [visited]);

return (<AnimatedText style={style}>{text}</AnimatedText>)
}
组件.js
function Component({texts}) {
const [visitIndex, setVisitIndex] = React.useState(0);

useEffect(() => {
// code to reduce text scale one after another
// it will loop over the array of textScaleShared values
// passed to each component and update it
if (visitIndex === texts.length) {
return;
}

const timerId = setTimeout(() => {
setVisitIndex((idx) => idx + 1);
}, revealDuration);

return () => {
clearTimeout(timerId);
};
}, []);
return texts.map((text, index) => (<AnimatedTextItem text={text} visited={visitIndex === index}/>))
}

关于reactjs - 如何为一组组件创建一个动态的 React 钩子(Hook)数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67590211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com