reactjs - 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
,并且可能有更好的方法来实现我想要实现的目标。
解决方案
每次渲染组件时都会调用渲染循环中的任何内容。
// 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]);
推荐阅读
- mediawiki - OATHAuth mediawiki 插件中的 OATHAuthAlias / OATHAuth.alias.php 是做什么用的?
- scala - 在 Scala 中找不到依赖项
- python - 检查字符串是否是数字的二进制表示法
- datetime - 如何在jooq中将双精度转换为日期
- gnuplot - gnuplot 5.0.3 中的 xrange 问题
- python-3.x - IBM Spectrum LSF - 访问不同 HPC 节点上的多个 GPU
- java - Spring Boot 与 Spock 的集成测试:存根方法返回 null
- android - Android DJI SDK 创建海量日志文件
- reactjs - ReactJS/TypeScript - 类型“HTMLElement”错误中不存在属性“文件”
- scala - 在 scala 中,如何将期货列表转换为返回第一个成功未来的未来?