[英]pass state data from child to nested component
const Child = ({ ChildIndex }) => {
const [index, setIndex] = useState();
<FlatList
contentContainerStyle={styles.contentContainer}
ref={flatListRef}
scrollEnabled
showsVerticalScrollIndicator={false}
data={videos}
onMomentumScrollEnd={(e) => {
setIndex(Math.round(e.nativeEvent.contentOffset.x / width));
}}
onEndReachedThreshold={Platform.OS === "ios" ? 0 : 1}
/>;
};
const Parent = () => {
const [currentChildIndex, setCurrentChildIndex] = useState();
<Child ChildIndex={ChildIndex} />;
};
我想在父组件中获取更新的currentChildIndex
。 它在第一次加载时显示索引,但之后不会更新。 试图查看 useState 钩子但不是运气
您只需要传递setCurrentChildIndex
即可:
const Parent = () => {
const [currentChildIndex, setCurrentChildIndex] = useState();
useEffect(() => {
console.log("CurrentChildIndex has been updated", currentChildIndex);
}, [currentChildIndex]);
return <Child setCurrentChildIndex={setCurrentChildIndex} />;
};
并在您的Child
组件中使用它而不是setIndex
const Child =({setCurrentChildIndex})=>{
<FlatList
contentContainerStyle={styles.contentContainer}
ref={flatListRef}
scrollEnabled
showsVerticalScrollIndicator={false}
data={videos}
onMomentumScrollEnd={e => {
setCurrentChildIndex(Math.round(e.nativeEvent.contentOffset.x / width));
}}
onEndReachedThreshold={Platform.OS === 'ios' ? 0 : 1}
/>
/>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.