3 回答

TA貢獻1909條經驗 獲得超7個贊
或者,將任何通用邏輯分解為一個實用函數,例如SpeechUtil.ts
,一個包含此共享邏輯和每個實用函數的全新文件,并將它們導出。然后,每個組件分別導入它們。這樣可以確保如果您更新該邏輯,它會影響兩個組件

TA貢獻1776條經驗 獲得超12個贊
你可以使用 React.createRef 來達到這個目的。下面是一個示例代碼。
import Speech from './Speech';
type Props = {}
type States = {}
export default class SpeechIOS extends Component<Props, States> {
constructor(props: Props) {
super(props);
this.speech = React.createRef();
}
// render
render() {
...
return (<Speech ref={this.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.speech.current.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..
};
}

TA貢獻1906條經驗 獲得超3個贊
您應該定義一個頂級組件來定義共享的道具和方法,并使用它們來呈現您的 ios 或 android 組件。把道具和方法傳給孩子。這是在反應中優(yōu)于繼承的組合。例子:
class Speech extends React.Component {
state ={shared: 'state'}
sharedMethod = () => {
this.setState({blah: 'blah})
}
render() {
const Root = Platform.select({
ios: SpeechIOS,
android: SpeechAndroid
})
return <Root onClick={this.sharedMethod} shared={this.state.shared}/>
}
}
添加回答
舉報