【问题标题】:"unrecognized selector sent to instance" when setting a property on react-native在 react-native 上设置属性时“无法识别的选择器发送到实例”
【发布时间】:2017-02-19 09:53:56
【问题描述】:

我正在尝试将我的 Swift 视图与我的 React-Native 项目链接起来。我想出了如何显示它,但是现在当我尝试设置属性时,我收到了以下错误消息:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Switch setMessage:]: unrecognized selector sent to instance 0x7f96b270de70'

在我的 react-native 代码中,我正在做:

const SwitchNative = requireNativeComponent('Switch', Switch);

class Switch extends Component {
  render() {
    return (
        <SwitchNative message="message will be" style={this.props.style} />
    );
  }
}

然后在我的 SwiftBridge 中执行此操作:

// SwiftBridge.h

#import "RCTView.h"

@interface SwitchBridge : RCTView

  @property (nonatomic, assign) NSString *message;

@end

// SwiftBridge.m

#import "RCTBridgeModule.h"
#import "RCTViewManager.h"
#import "SwitchBridge.h"

@interface RCT_EXTERN_MODULE(SwitchManager, RCTViewManager)

  RCT_EXPORT_VIEW_PROPERTY(message, NSString)

@end

最后我在我的 Swift 课程中拥有了这个 Switch.swift:

...
public func setMessage(message: String) {
  NSLog("It's working well");
}
...

不知道为什么它找不到我的setMessage 函数。

【问题讨论】:

    标签: ios swift reactjs react-native


    【解决方案1】:

    React Native 正在尝试调用 -[Switch setMessage:],但您已在没有任何参数的情况下定义了 -[Switch setMessage]。为您的 Swift 方法签名添加一个参数:

    public func setMessage(_ message: String)
    

    根据您的 Swift 版本,您可能还需要使用 @objc 注释您的方法。

    【讨论】:

    • 啊,我也试过了,也没用。我编辑了我的问题。如何注释?
    • 如果其他人想知道,@objc(setMessage:) func setMessage(_ message: String)
    【解决方案2】:

    正确的语法现在很快,

    @objc(setMessage:)
    public func setMessage(message: String) {
      NSLog("It's working well");
    }
    

    这是 Swift > 3.2、Mac High Sierra 和 React Native >= 0.43 的变化

    【讨论】:

      【解决方案3】:

      对于任何可能正在搜索从 React-Native 传递对象数组的人(我在这样做时遇到了这个问题):

      YourView.h:

      @interface YourView : RCTView
      
      @property (nonatomic, assign) NSMutableArray *markers;
      
      @end
      

      YourView.m:

      ...
      RCT_CUSTOM_VIEW_PROPERTY(markers, NSMutableArray, YourView)
      {
        [view setMarkers:json];
      }
      

      YourView.swift:

      @objc(setMarkers:)
      public func setMarkers(json: NSMutableArray) {
          
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-28
        相关资源
        最近更新 更多