首页 > 解决方案 > 从 export const 调用类函数 react native

问题描述

我想从 webViewEventHandlers.js 中的 export const 类调用 ComposeBox.js 中的 handleSend 函数

ComposeBox.js

class ComposeBox extends PureComponent<Props, State> {

handleSend = () => {
    const { dispatch } = this.props;
    const { message } = this.state;
    dispatch(addToOutbox(this.getDestinationNarrow(), message));

    this.setMessageInputValue('');
  };

export default connect((state: GlobalState, props) => ({
  auth: getAuth(state),
}))(ComposeBox);

webViewEventHandlers.js

import ComposeBox from '../compose/ComposeBox';

export const handleMessageListEvent = () => {

case 'wizrep':
      ComposeBox.handleSend();
      break;

我收到以下错误

在此处输入图像描述

标签: reactjsreact-native

解决方案


React 手册指出:所有 React 组件在其 props 方面都必须像纯函数一样工作。

这意味着尝试创建 Component 的实例并将其视为对象会给您带来非常困难的时间。

根据您发送的代码片段,我可以想象一些可能的解决方法:

  • 从 ComposeBox 内部调用 handleMessageListEvent,将 handleSend 函数作为参数传递。
  • 将消息设置为 Redux 状态的一部分而不是组件,并从 webViewEventHandlers 调度操作。
  • 使 handleMessageListEvent 成为 ComposeBox 组件的一部分。

推荐阅读