在 iOS/macOS 中将 React Native 的原生组件制作到正确的位置、正确的道具并接受鼠标点击

Make native component for React Native in iOS/macOS to proper position, proper props and accept mouse click

提问人:Jihoo Byeon 提问时间:10/21/2023 更新时间:10/21/2023 访问量:13

问:

我正在为 React Native 制作一个简单的“复选框”原生组件。它适用于 macOS,但它的方式与 iOS 类似。

这是我的代码:

RNCCheckBox.m

#import <AppKit/AppKit.h>

@interface RNCCheckBox : NSView

@property (nonatomic, copy) NSString *title;
@property (nonatomic, assign) BOOL isSelected;

@end

@implementation RNCCheckBox

- (instancetype)init
{
    self = [super initWithFrame:NSMakeRect(50, -100, 50, -100)]; // weird value, but this works, positive values does not.
    if (self) {
        _title = @"";
        _isSelected = YES; // or NO
        NSButton *cb = [[NSButton alloc] initWithFrame:self.frame];
        [cb setTitle:_title];
        [cb setButtonType:NSButtonTypeSwitch];
        [cb setTarget:self];
        [cb setState:_isSelected];
        [cb setAction:@selector(clicked:)];
        [self addSubview:cb];

    //  [cb performClick:self]; this works, but mouse click does not.
    }
    return self;
}

- (void)setTitle:(NSString *)title
{
    if (![_title isEqual:title])
        _title = [title copy];
}

- (void)setIsSelected:(BOOL)isSelected
{
    if (_isSelected != isSelected)
        _isSelected = isSelected;
}

- (void)clicked:(id)sender // does not invokes
{
    NSButton *cb = (NSButton *)sender;
    [cb setState:_isSelected];
}

@end

RNCCheckBoxManager.m

#import <React/RCTViewManager.h>
#import "RNCCheckBox.h"

@interface RNCCheckBoxManager : RCTViewManager
@end

@implementation RNCCheckBoxManager

RCT_EXPORT_MODULE()

- (NSView *)view
{
    NSView *view = [RNCCheckBox new];
    return view;
}

RCT_EXPORT_VIEW_PROPERTY(title, NSString *)
RCT_EXPORT_VIEW_PROPERTY(isSelected, BOOL)

@end

CheckBox.tsx

import React from 'react';
import { requireNativeComponent } from "react-native";

const RNCCheckBox = requireNativeComponent('RNCCheckBox');

export class CheckBox extends React.Component<{ title: string, isSelected: boolean }> {
    render() {
        return (
            <RNCCheckBox { ...this.props } /> // props does not injected
        );
    }
}

module.exports = CheckBox;

App.tsx 在我的应用程序中:

import React from 'react';
import { View } from 'react-native';
import { CheckBox } from 'react-native-my-checkbox';

export default class App extends React.Component<undefined, { checked: boolean }> {
    constructor(props: undefined) {
        super(props);
        this.state = { checked: false };
    }

    render() {
        return (
            <View>
                <CheckBox title={'Test'} isSelected={ this.state.checked } />
            </View>
        );
    }
}

这些代码无法正常工作 - 出现复选框,但不可单击,并且未注入 props。

此外,它的位置不遵循它的 ,所以我必须手动设置它。<View />initWithFrameenter image description here

如果我更改为 ,左上角仅显示蓝点。init

我哪里做错了?

objective-c appkit react-native-macos

评论


答: 暂无答案