我正在将原生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=0
和height=0
(至少这样说是NSLog(String(describing: frame.size.height))
)。iOS MapView example指定不覆盖框架,因为React Native会对此进行设置。我不知道框架是错误的还是在这里缺少其他上下文?我尝试按照#2948#15097的指示进行操作,但没有任何帮助。
最佳答案
我在这里找到错误。事实证明,您必须在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>
);
}
}