首页 > 解决方案 > 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>
    );
};

入口.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,并且可能有更好的方法来实现我想要实现的目标。

标签: reactjsreact-nativeandroid-viewpagerreact-navigationreact-native-elements

解决方案


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

    // 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]);

推荐阅读