[英]How do I call/execute a function from another component in react native?
如何在 React Native 中調用當前組件中的其他組件函數? 它們也都使用不同的腳本。
任何人都知道如何在本機反應中做到這一點?
//ClassOne.js
class ClassOne extends React.Component {
constructor(props) {
super(props);
}
setValue(){
}
}
//ClassTwo.js
class ClassTwo extends React.Component {
constructor(props) {
super(props);
}
callSetValue(){
ClassOne.setValue(); HOW???
}
}
您可以將 ClassOne.setValue 作為屬性傳遞給 ClassTwo。
//ClassOne.js
class ClassOne extends React.Component {
constructor(props) {
super(props);
}
setValue(){
// Do stuff
}
}
//ClassTwo.js
class ClassTwo extends React.Component {
constructor(props) {
super(props);
}
callSetValue(){
if (this.props.onSetValue) this.props.onSetValue(); // this can be set to any function, including ClassOne's setValue
}
}
除非您要調用的函數是靜態的,否則您必須在要調用該函數的范圍內實例化您想要的任何類。 假設在 ClassTwo 中您想調用 ClassOne 中的方法...在 ClassTwo 中實例化 ClassOne 的一個實例,然后使用該對象調用該函數。
顯然,它不是ReactJS 中的推薦方式,即使是 React-Native。 也許你想遵循面向對象的編程規則,但在這里我們在 ReactJS 中進行了全功能開發。 對於這種情況,我更喜歡使用輔助函數,並且在這兩個類中,我都導入並使用了輔助函數:
// set value helper function
export const setValueHelper = () => {
// do something
};
然后在課堂上:
import { setValueHelper } from 'helpers';
//ClassOne.js
class ClassOne extends React.Component {
constructor(props) {
super(props);
}
setValue(){
setValueHelper();
}
}
import { setValueHelper } from 'helpers';
//ClassTwo.js
class ClassTwo extends React.Component {
constructor(props) {
super(props);
}
setValue(){
setValueHelper();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.