【发布时间】:2020-03-18 02:38:43
【问题描述】:
背景
我创建了一个功能齐全的组件。组件有state和props,里面有很多方法。根据操作系统(ios / android),我的组件应该以不同的方式工作。所以我通过if 语句解决了这个问题,如下所示。
if( platform.os == 'ios') { ... } else { ... }
问题是随着代码量的增加,可读性出现问题,我决定为IOS和Android分别制作一个组件。首先想到的是继承,因为 ES6 和 Typescript 支持类。概念图是这样的。
但是,React does not recommend inheritance。所以我只是打算将 props 覆盖的函数交给 SpeechIOS 组件的渲染函数中的 Speech 组件。
代码如下。
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) { ... };
...
}
SpeechIOS.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 组件中的一些功能。
那么,如何解决这个问题呢?我应该使用继承吗?
【问题讨论】:
标签: javascript reactjs typescript inheritance