簡體   English   中英

在reactjs中,如何從另一個組件調用方法?

[英]In reactjs how can I call a method from another component?

只是嘗試reactjs並遇到了我想在另一個組件上調用方法的情況:

class MyComp extends React.Component {

callMe(){
...
       }
}

所以mycomp2:

import MyComp from 'myComp';

class MyComp2 extends React.Component {

test(){
       MyComp.callMe();
      }
}

我怎樣才能做到這一點 ?

不能。 您不能在react組件中做到這一點。 唯一的方法是將該功能移交給他們的共同祖先。

當然,還有另一種方法,為什么不考慮使用redux? 讓我們通過redux狀態來響應組件對話。 這樣,您將永遠不會遇到這個難題。

如果方法callMe不使用this ,則可以將其清除為靜態狀態,以使用它。

class MyComp extends React.Component {

    static callMe(){
    ...
    }
}

如果沒有,您可以使用ref使其起作用。

您可能需要: https : //facebook.github.io/react/docs/refs-and-the-dom.html

這取決於您的組件之間如何相互關聯。 如果一個是父母,另一個是孩子,則該函數可以作為道具從父母傳遞給孩子,例如

class Parent extends React.Component {
    callMe() {
        console.log('called');
    }

    render() {
        return (
            <Child doSomething={() => this.callMe()} />
        );
    }
}

class Child extends React.Component {
    render() {
         <button onClick={this.props.doSomething}>Calls the parent fn</button>
    }
}

或者,如果它們不是父子關系,則需要引入一個父組件,函數可以在其中生活,然后以相同的方式通過道具傳遞該組件。

如果這兩種方法都不適合,那么請讓我們知道您想要實現的行為需要這樣做,並且很可能有另一種方式來構造您的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM