背景
我创建了一个功能齐全的组件。组件有state和props,里面有很多方法。根据操作系统(ios/android),我的组件应该以不同的方式工作。所以我通过下面的 if
语句解决了这个问题。
if(platform.os == 'ios') { ... } else { ... }
问题是随着代码量的增加,可读性出现了问题,我决定分别为IOS和Android做一个组件。首先想到的是继承,因为 ES6 和 Typescript 支持 Class。概念图是这样的。
然而,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/