javascript - React组件继承使用父方法和子方法

标签 javascript reactjs typescript inheritance

背景

我创建了一个功能齐全的组件。组件有state和props,里面有很多方法。根据操作系统(ios/android),我的组件应该以不同的方式工作。所以我通过下面的 if 语句解决了这个问题。

if(platform.os == 'ios') { ... } else { ... }

问题是随着代码量的增加,可读性出现了问题,我决定分别为IOS和Android做一个组件。首先想到的是继承,因为 ES6 和 Typescript 支持 Class。概念图是这样的。

enter image description here

然而,React does not recommend inheritance .所以我只是打算在 SpeechIOS 组件的渲染函数中将 props 覆盖的功能交给 Speech 组件。

代码如下。

语音.tsx

type Props = {
  team: number,
  onSpeechResults: (result: string) => void
  ...
}
type States = {
  active: boolean;
  error: string;
  result: string;
  ...
};

export default class Speech extends Component<Props,States> {
  state = { ... };
  constructor(props: Props) {
    super(props);
    ...
  }

  // render
  render() {
    ...
    return (
      <ImageBackground source={require("../images/default-background.jpeg")} style={styles.full}>
        ...
      </ImageBackground>
    );
  }
  sendCommand = (code: number, speed: number, callback?: () => void) => { ... }
  getMatchedSpell = (spellWord: string): { code: number, speed: number } => { ... }
  onSpeechResults(e: Voice.Results) { ... };
  ...
}

语音IOS.tsx

import Speech from './Speech';

type Props = {}
type States = {}
export default class SpeechIOS extends Component<Props,States> {
  constructor(props: Props) {
    super(props);
    ...
  }

  // render
  render() {
    ...
    return ( <Speech team="1" onSpeechResults={this.onSpeechResults}></Speech> );
  }

  sayHello() {
    console.log("Hello!!");
  }

  // I want that Speech Component call this onSpeechResults function
  onSpeechResults(result: string) {
    this.setState({...});
    let temp = this.getMatchedSpell( ... ); // which is in Speech Component
    this.sendCommand( 10, 100 ... ); // which is in Speech Component
    this.sayHello(); // which is in SpeechIOS component only
    ... other things..
  };
}

问题。

如您所见,SpeechIOS 组件中的onSpeechResults 使用了Speech 组件中的一些函数,同时也使用了SpeechIOS 组件中的一些函数。

那么,如何解决这个问题呢?我应该使用继承吗?

最佳答案

或者,将任何通用逻辑分解为实用程序函数,如 SpeechUtil.ts,这是一个包含此共享逻辑和每个实用程序函数的全新文件,并将它们导出。然后,每个组件分别导入它们。这确保如果您更新该逻辑,它会影响两个组件

关于javascript - React组件继承使用父方法和子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58987199/

相关文章:

node.js - 从 Node 事件处理程序内调用函数

javascript - 将 html block 写成字符串

javascript - 您可以在 TinyMCE 4.x 编辑器上切换只读吗

reactjs - 将 Electron 与React应用程序一起使用时`require is not defined`错误

javascript - webpack/babel/react - 意外的 token 错误

reactjs - React onClick 在加载时触发多次,并且组件 props 中不包含回调函数

javascript - 相当于 mousedown 的 JS 触摸事件

javascript - 如何在后退/前进或刷新后保留数据表中的过滤器

typescript :允许泛型类型只能是具有 'string' 属性的对象

visual-studio - 使用不同版本的项目,该项目是使用不同版本的 Typescript 构建的