React Native 将状态数据从子组件传递到嵌套组件

t0ybt7op  于 2022-11-25  发布在  React
关注(0)|答案(1)|浏览(128)

第一个
我想在父组件中得到更新的currentChildIndex。它在第一次加载时显示索引,但之后不会更新。尝试查找useState钩子,但没有找到

nhaq1z21

nhaq1z211#

您只需要传递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}
    />
/>
}

相关问题