reactTag
方法中的AccessibilityInfo.setAccessibilityFocus(reactTag)
参数是什么? React Native 文档不提供有关此参数的任何信息:
将可访问性焦点设置为 React 组件。在 Android 上,这等效 到 UIManager.sendAccessibilityEvent(reactTag, UIManager.AccessibilityEventTypes.typeViewFocused);.
我没有任何
Objective-C
和Java
的背景。举一个小例子会更受赞赏。谢谢!!!
reactTag
只是一个数字,React 使用它来识别应用程序中的视图对象。它是 findNodeHandle
函数的结果,该函数以视图引用作为参数。
这是一个有关如何使用它的简单示例:
import React, {Component} from 'react'
import {
...
findNodeHandle,
...
} from 'react-native';
class Sample extends React.Component {
constructor(props) {
super(props)
this.viewRef = null;
}
...
componentDidMount() {
if (this.viewRef) {
const reactTag = findNodeHandle(this.viewRef);
AccessibilityInfo.setAccessibilityFocus(reactTag);
}
}
render() {
return (
<View ref={el => { this.viewRef = el }}>
...
</View>
)
}
}
功能组件的示例。当组件加载时,屏幕阅读器焦点将设置为顶部元素。
const myComponent = () => {
const topRef = useRef<View>(null);
useEffect(() => {
if (topRef.current) {
const reactTag = findNodeHandle(topRef.current);
reactTag && AccessibilityInfo.setAccessibilityFocus(reactTag);
}
});
return (
<>
<View ref={topRef}>Top</View>
<View>Middle</View>
<View>Bottom</View>
</>
)
}
注意,此解决方案的一个大问题是您希望关注的组件需要能够获取引用。如果您使用的是库,例如 React Native Paper,这些组件可能无法直接获取引用。如果不这样做,您将需要使用普通的 React Native 组件。或者针对添加引用传递的库进行 PR。