React-Native:无法触发 Native UIButton 触摸事件

Posted

技术标签:

【中文标题】React-Native:无法触发 Native UIButton 触摸事件【英文标题】:React-Native: Cannot trigger Native UIButton touch event 【发布时间】:2017-08-20 16:10:36 【问题描述】:

我正在将一个原生 Swift 模块桥接到 React Native。我创建了一个UIView,它创建了一个带有目标处理程序的UIButton。它可以正确呈现所有内容,但是单击该按钮不会触发任何内容。我在这里主持了一个演示:https://github.com/esbenp/react-native-swift-test

我的原生模块相当简单:https://github.com/esbenp/react-native-swift-test/blob/master/ios/TestModule.swift

let Button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
Button.setTitleColor(UIColor.blue, for: .normal)
Button.setTitle("Press me", for: .normal)
Button.addTarget(self, action: #selector(TestModule.onClick), for: .touchUpInside)

self.addSubview(Button)

我使用经理桥接它:https://github.com/esbenp/react-native-swift-test/blob/master/ios/TestModuleManager.m

#import <React/RCTViewManager.h>
#import "ReactNativeSwiftTest-Swift.h"

@interface TestModuleManager : RCTViewManager
@end

@implementation TestModuleManager

RCT_EXPORT_MODULE()

- (UIView *)view

  return [[Parent alloc] init];


@end

然后在JS中运行:https://github.com/esbenp/react-native-swift-test/blob/master/index.ios.js

我不是 iOS 专家,但它似乎与框架有关。如果我采用相同的本机模块并在普通的 iOS 项目UIViewController 中使用它,如下所示:

override func viewDidAppear(_ animated: Bool) 
    super.viewDidAppear(animated)

    let Button = TestModule(frame: CGRect(x: 0, y: 0, width: 500, height: 500))

    self.view.addSubview(Button)

它有效。我假设这是因为 React Native 创建的框架是 width=0height=0(至少在我 NSLog(String(describing: frame.size.height)) 时是这样说的)。

iOS MapView example 指定不覆盖框架,因为 React Native 会设置它。我不知道框架是错误的还是我在这里错过了其他一些上下文?我尝试按照 #2948 #15097 中的说明进行操作,但没有任何帮助。

【问题讨论】:

【参考方案1】:

我在这里发现了错误。事实证明,您必须在 JS 端的实际原生组件中添加 flex: 1 才能正确填充框架。

之前

export default class ReactNativeSwiftTest extends Component 
  render() 
    return (
      <View style=styles.container>
        <Test />
      </View>
    );
  

之后

export default class ReactNativeSwiftTest extends Component 
  render() 
    return (
      <View style=styles.container>
        <Test style=flex: 1 />
      </View>
    );
  

【讨论】:

以上是关于React-Native:无法触发 Native UIButton 触摸事件的主要内容,如果未能解决你的问题,请参考以下文章

iOS 上的自动更正不会在 react-native 中触发 onChangeText

React-Native 无法解析模块

React-native 链接无法正常工作

React-Native 远程调试器无法在 iPhone 上运行

文件无法脱机工作(React-Native)

无法在我的项目中解析“react-native”