【问题标题】:onFocus and onBlur doesnt work , react-nativeonFocus 和 onBlur 不起作用,反应原生
【发布时间】:2021-06-23 02:56:31
【问题描述】:

我正在尝试使用 react-native 构建一个 androidTV 应用程序,并且我遵循了文档,但是无论我做什么,似乎 onFocus 和 onBlur 对我都不起作用,这是代码:

const App = () => {
  return (
    <View>
      <TouchableHighlight
        hasTVPreferredFocus={true}
        accessible={true}
        onFocus={() => alert('focus')}
        onBlur={() => alert('blur')}
        onPress={() => alert('press')}>
        <Text>This is a text</Text>
      </TouchableHighlight>
      <Button title="title" />
    </View>
  );
};

我还添加了hasTVPreferredFocusaccessible 以确保我没有错过任何内容。

【问题讨论】:

  • import {TouchableHighlight,Button} from "react-native"; 使用这条线,它会很适合你。
  • @MohamedBdr 我已经导入了它们,组件本身工作正常,但道具 {onBlur , onFocus} 是问题
  • 你能告诉我你想做什么,所以如果你点击This is a text你会发现按下警报是你想要的还是你想要的按钮来做这个行为?
  • @MohamedBdr 我想检测组件何时聚焦以及何时离开聚焦,因此当用户在 androidTv 上使用 D-pad 移动时,我可以更改样式

标签: javascript react-native native android-tv


【解决方案1】:

我发现了如何修复它,似乎npx react-native init &lt;ProjectName&gt; 不完整并且其中有一些丢失的文件。 相反,我使用了react-native init &lt;ProjectName&gt; --template=react-native-tvos,它起作用了!我认为 tvos 版本更适合用于电视开发。

【讨论】:

    【解决方案2】:

    它不起作用,因为该组件不监听这些事件,请查看文档:

    https://reactnative.dev/docs/touchablehighlight

    【讨论】:

    • 在文档中它没有将“onPress”显示为道具,但它可以工作。也在这里github.com/dev-seb/react-native-tv-demo/blob/master/src/… 这个家伙在可触摸的高光上使用了 onFocus 和 onBlur
    • 是的,但它是一个“可触摸”,很明显它将是一个可按压组件,在他们使用它的示例中......
    • here ,它说我们可以在可触摸的 mixin 上使用 onFocus 和 onBlur。同样在 vs-code 中,它建议 onBlur 和 onFocus 仅在可触摸的 mixin 上,这是强化我们可以使用上述道具这一事实的另一个原因
    • 我们在这里,正在考虑这个失败..如果你还没有,请尝试使用 useRef() 挂钩从另一个事件发送焦点..
    • 它确实有 onFocus 和 onBlur 道具,文档也这么说,只是没有在此处列出,而是在 TouchableWithoutFeedback 中列出,文档说 touchableHighlight 继承了 TouchableWithoutFeedback 道具。
    【解决方案3】:

    import React from 'react';
    import { TextInput } from 'react-native';
    import { styles } from './styles';
    
    const Input = (props) => {
      const [focused, setFocused] = React.useState(false);
      return (
        <TextInput
          {...props}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          style={focused ? styles.inputFocused : styles.input}
        />
      );
    };
    
    export default Input;

    如果你的道具覆盖了 onFocus 函数,只需像这样把它放在头上

    【讨论】:

    • 我想在 &lt;TouchableHighlight&gt; 或任何其他可触摸的 mixin 上使用 onFocus 和 onBlur
    猜你喜欢
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 2011-03-20
    相关资源
    最近更新 更多