React Native의 초점 관리 방법

WBOY
풀어 주다: 2024-09-12 10:31:32
원래의
246명이 탐색했습니다.

TV용 React Native 앱에서 포커스 관리를 처리할 때 개발자는 다음과 같은 5가지 익숙한 단계(슬픔)를 겪게 될 수 있습니다. ? ? ? ?

포커스 관리는 다양한 포커스 관리 기술로 이어진 TV 플랫폼 간의 단편화로 인해 TV 애플리케이션 개발에서 독특한 과제입니다. 개발자는 포커스 관리를 위한 여러 전략을 만들고 채택해야 했으며 종종 플랫폼 간 추상화와 함께 플랫폼별 솔루션을 저글링해야 했습니다. 포커스의 과제는 포커스가 올바르게 처리되도록 보장하는 것뿐만 아니라 플랫폼 차이를 처리하는 것입니다. Android TV와 Apple의 tvOS에는 고유한 네이티브 포커스 엔진이 있습니다. 이에 대한 자세한 내용은 제 동료 @hellonehha가 작성한 이 기사에서 읽어보실 수 있습니다.

ays Of Managing Focus In React Native

원래 TV 관련 문서와 API는 기본 React Native 문서의 일부였습니다. 이제 대부분의 TV 관련 콘텐츠가 React-native-tvos 프로젝트로 이동되었습니다.

ays Of Managing Focus In React Native

반응 네이티브 TVOS

"react-native": "npm:react-native-tvos@latest"

react-native-tvos 프로젝트는 Apple TV 및 Android TV 플랫폼 지원에 특히 중점을 두고 핵심 React Native 프레임워크에 대한 추가 기능과 확장 기능을 제공하는 오픈 소스 패키지입니다. 이 프로젝트의 변경 사항 대부분은 리모컨의 D패드를 사용하여 SmartTV에서 포커스 기반 탐색을 처리하는 데 중점을 두고 있습니다. 이 프로젝트는 (놀라운!) Doug Lowder에 의해 유지 관리되며 일반적으로 React Native TV 애플리케이션에서 포커스 관리를 처리하는 기본 방법으로 권장됩니다.

그러나 커뮤니티에서 유지 관리하는 많은 프로젝트와 마찬가지로 React-native-tvos 프로젝트는 개발자의 요구에 따라 발전해 왔으며 이제 포커스를 처리하는 여러 가지 방법이 있습니다. React-native-tvos가 제공하는 기존 구성 요소에 대한 추가 구성 요소와 향상된 기능을 살펴보겠습니다.

1. TV포커스가이드뷰

예를 들어 TVFocusGuideView 구성 요소 내부에 렌더링된 10개의 Pressable 구성 요소로 구성된 그리드는 다음과 같습니다.


import { TVFocusGuideView } from 'react-native';

const TVFocusGuideViewExample = () => {
  const [focusedItem, setFocusedItem] = useState(null);

  const renderGridItem = number => (
    <Pressable
      style={[styles.gridItem, focusedItem === number && styles.focusedItem]}
      key={number}
      onFocus={() => setFocusedItem(number)}
      onBlur={() => setFocusedItem(null)}>
      <Text style={styles.gridItemText}>{number}</Text>
    </Pressable>
  );

  return (
    <>
      <Header headerText="Movies" />
      <TVFocusGuideView trapFocusLeft style={styles.grid}>
        {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(num => renderGridItem(num))}
      </TVFocusGuideView>
    </>
  );
};
로그인 후 복사

TVFocusGuideView는 포커스를 처리하는 데 도움이 되는 몇 가지 소품을 허용합니다.ays Of Managing Focus In React Native

목적지 소품

TVFocusGuideView를 사용하면 TVFocusGuideView의 '대상'으로 등록할 구성 요소 배열을 설정할 수 있습니다. 예시를 살펴보겠습니다.

<TVFocusGuideView destinations={[]}>
로그인 후 복사

목적지 소품을 항목 8(destinations={[item8Ref.current]})에 대한 참조로 설정하면 TVFocusGuideView를 처음 탐색할 때 초점이 항목 8로 이동합니다.

TrapFocus 소품 ays Of Managing Focus In React Native

이 소품은 주어진 방향에 대해 포커스가 상위 구성 요소에서 벗어나지 않도록 보장합니다. 이 소품은 포커스가 주어진 방향에 대해 상위 구성 요소에서 벗어나지 않도록 보장합니다. 예시를 살펴보겠습니다.

<TVFocusGuideView trapFocusUp|trapFocusDown|trapFocusLeft|trapFocusRight  />
로그인 후 복사

trapFocusLeft 소품을 사용하면 더 이상 컨테이너 외부에서 왼쪽으로 탐색할 수 없습니다.

자동 초점 소품 ays Of Managing Focus In React Native

자동 초점이 true로 설정되면 TVFocusGuideView가 초점을 맞출 수 있는 첫 번째 하위 항목으로 초점을 리디렉션하여 초점을 관리합니다. 또한 마지막으로 초점을 맞춘 어린이를 기억하고 후속 방문 시 해당 어린이에게 초점을 리디렉션합니다. 이 prop을 Destinations Prop과 함께 사용하면 Destinations Prop에 의해 설정된 구성 요소가 우선 적용됩니다. 예시를 살펴보겠습니다.

 <TVFocusGuideView autoFocus />
로그인 후 복사

이 소품이 없으면 Header 구성 요소에서 TVFocusGuideView 포커스로 가장 가까운 구성 요소로 이동할 때 항목 3(Android 근접 기반 내장 포커스 엔진에 따라)

    자동 초점 소품을 사용하면 항목 1로 이동합니다

2. Touchable

With the react-native-tvos, the Touchable component's ( TouchableWithoutFeedback, TouchableHighlight and TouchableOpacity) include additional code to detect focus changes and properly style the components when focused. It also ensures that the appropriate actions are triggered when the user interacts with the Touchable views using the TV remote control.

Specifically, the onFocus event is fired when the Touchable view gains focus, and the onBlur event is fired when the view loses focus. This enables you to apply unique styling or logic when the component is in the focused state that doesn’t come out of the box with core React Native.

Additionally the onPress method has been modified to be triggered when the user selects the Touchable by pressing the "select" button on the TV remote (the center button on the Apple TV remote or the center button on the Android TV D-Pad) and the onLongPress event is executed twice when the "select" button is held down for a certain duration.

3. Pressable

Like Touchable, the Pressable component been enhanced to allow it to accept the onFocus and onBlur props.
Similar to the ‘pressed’ state that is triggered when a user presses the component on a touchscreen, the react-native-tvos Pressable component introduces a focused state that becomes true when the component is focused on the TV screen.

Here’s an example when using the Pressable and Touchable components from React Native core and they do not accept / execute the onFocus and onBlur props:

ays Of Managing Focus In React Native

Using the same Pressable and Touchable components from react-native-tvos they accept and execute the onFocus and onBlur props:

ays Of Managing Focus In React Native

4. hasTVPreferredFocus prop

Some React Native components have the hasTVPreferredFocus prop, which helps you prioritise focus. If set to true, hasTVPreferredFocus will force the focus to that element. According to the React Native docs these are the current components that accept the prop:

ays Of Managing Focus In React Native

However, if you are using react-native-tvOS, there are a lot more components that accept this prop:

<View hasTVPreferredFocus />
<Pressable hasTVPreferredFocus />
<TouchableHighlight hasTVPreferredFocus />
<TouchableOpacity hasTVPreferredFocus />
<TextInput hasTVPreferredFocus />
<Button hasTVPreferredFocus />
<TVFocusGuideView hasTVPreferredFocus />
<TouchableNativeFeedback hasTVPreferredFocus />
<TVTextScrollView hasTVPreferredFocus />
<TouchableWithoutFeedback hasTVPreferredFocus />
로그인 후 복사

Lets look at an example:

  • Setting the hasTVPreferredFocus prop to true for Pressable 2 causes focus be on Pressable 2
  • Changing it to be true when we are on Pressable 3 causes focus to move to Pressable 3

ays Of Managing Focus In React Native

5. nextFocusDirection prop

The nextFocusDirection prop designates the next Component to receive focus when the user navigates in the specified direction helping you handle focus navigation. When using react-native-tvos, this prop is accepted by the same components that accept the hasTVPreferredFocus prop (View, TouchableHighlight, Pressable, TouchableOpacity, TextInput, TVFocusGuideView, TouchableNativeFeedback, Button). Lets look at an example:

nextFocusDown={pressableRef3.current}
nextFocusRight={pressableRef5.current}>
로그인 후 복사
  • Setting the nextFocusDown prop to Pressable 3 causes focus to move to Pressable 3 when the focus moves down
  • Setting the nextFocusRight prop to Pressable 5 causes focus to move to Pressable 5 when the focus moves right

ays Of Managing Focus In React Native

Conclusion

When it comes to handling focus management, there is no one-size-fits-all solution for React Native TV apps. The approach ultimately depends on the specific needs and requirements of your project. While the react-native-tvos provides a useful cross-device abstractions, you may have to adopt platform-specific solutions to handle common fragmentation issues across SmartTV platforms.

Take the time to explore these various focus management solutions so that you can deliver an intuitive focus handling experience for your users, regardless of the SmartTV platform they are using.

Related resources

  • https://dev.to/amazonappdev/tv-navigation-in-react-native-a-guide-to-using-tvfocusguideview-302i
  • https://medium.com/xite-engineering/revolutionizing-focus-management-in-tv-applications-with-react-native-10ba69bd90
  • https://reactnative.dev/docs/0.72/building-for-tv

위 내용은 React Native의 초점 관리 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!