React Native Viewpager 中的自动对焦输入

Auto focus Input within React Native Viewpager

我正在使用 React Native Viewpager 接收用户输入,然后移动到下一页按下按钮。重要的是要注意,移动到下一页是在按下按钮时发生的,而不是通过禁用的正常滚动。

我认为处理此问题的最佳方法是在 ViewPager 上设置一个状态,该状态将传播到子条目中。

ViewPager.tsx:

export default function ViewPager({ route, navigation }) {

    const ref: React.RefObject<ViewPager> = React.createRef();
    const [currentPage, setCurrentPage] = useState(0);

    let setEntryPage = (page: number) => {
        ref.current?.setPage(page);
        setCurrentPage(page);
    }


    return (
        <View style={{flex: 1}}>
            <ViewPager
                style={styles.viewPager}
                initialPage={0}
                ref={ref}
                scrollEnabled={false}
            >
                {
                    GlobalStuff.map((entry, index) => {
                        return (
                            <Entry
                                key={index}
                                index={index}
                                pagerFocusIndex={currentPage}
                                pagerLength={quizDeck?.litems.length!}
                                setEntryPage={setEntryPage}
                            />
                        )
                    })
                }
            </ViewPager>
        </View>
    );
};

Entry.tsx:

export function Entry(props: EntryProps) {

    const inputRef: React.RefObject<Input> = React.createRef();
    if (props.pagerFocusIndex === props.index) {
        inputRef.current?.focus();
    }

    return (
        <View>
            <Input
                // ...
                ref={inputRef}
            />
            <IconButton
                icon="arrow-right-thick"
                color={colorTheme.green}
                onPress={() => {
                    props.index !== props.pagerLength - 1 ?
                        props.setEntryPage(props.index + 1) :
                        props.navigation!.reset({ index: 0, routes: [{ name: recapScreenName as any }] });
                }}
            />
// ...

不幸的是,inputRef 似乎是 null,并且可能有更好的方法来实现我正在努力实现的目标。

每次渲染组件时都会调用渲染循环中的任何内容。

    // This is called on every render
    const inputRef: React.RefObject<Input> = React.createRef();
    
    // So is this, it's always null
    if (props.pagerFocusIndex === props.index) {
        inputRef.current?.focus();
    }

将副作用放在效果中。

    // Untested
    const inputRef = useRef();

    useEffect(() => {
        if (props.pagerFocusIndex === props.index) {
            inputRef.current?.focus();
        }
    }, [inputRef.current, props.pagerFocusIndex, props.index]);