2017-04-22 22 views
3

裏面我有一個這樣的組件:反應執行方法的成分

import React, { Component } from 'react'; 

class MyComponent extends Component { 

    constructor(props, context) { 
    super(props, context); 
    this.state = { 
     isActive: false, 
    } 
    } 

    showMyComponent() { 
    this.setState({ 
     isActive: true, 
    }); 
    } 

    hideMyComponent() { 
    this.setState({ 
     isActive: false, 
    }); 
    } 

    render() { 
    return (
     <div> 
     <h1>Compoent Here</h1> 
     </div> 
    ); 
    } 
} 

export default MyComponent; 

現在,我的index.js我加入幾個組件。

... 

<Header /> 
<Nave /> 

我現在可以做這樣的事情在這裏:

MyComponent.showMyComponent(); 

就像你通常調用一個函數?

如果不是,這是如何完成的?

+1

好像應該有不同的方法來此。你想達到什麼目的? –

+0

我不認爲這會起作用,您將不得不在類實例上調用該方法。 'MyComponent.showMyComponent'只能用於靜態方法,但是你的方法不是靜態的,而且也不是,因爲那樣它就無法訪問狀態。 –

+1

我歐米同意,請告訴我們的背景是什麼 –

回答

4

您可以使用引用。在您的render()方法中,您可以獲得參考文獻。例如

<MyComponent ref={ref => {this.myComponent = ref}}/> 

您需要創建一個字段myComponent並將其分配給它。這樣,您可以調用它像this.myComponent.showMyComponent()

看到這裏Refs and the DOM

1

使用狀態

您正在考慮反應錯誤。你不應該像這樣調用一個組件函數。

您可以將一個道具傳遞給將使組件隱藏或顯示的組件。

或將組件包裝在母公司的if中。使用父母狀態隱藏或顯示組件。

if (someCondition) { <MyComponent /> }

+0

那麼如果沒有條件......如果在某些時候我只想把它放在那裏?就像如果我沒有......

+0

必須有一個條件。如果有開關,必須有一個原因,因此一個條件。 –

1

這是可行的,即使有些人不喜歡這個選項,因爲它是不是正式的方式做出反應,真的。

您可以在組件類(例如Typeahead上的重置方法)上定義任何公共方法,並通過refs(如this.refs.myTypeahead.reset())調用這些公共方法。在大多數情況下,使用內置的React數據流而不是強制使用ref會更清楚。

但是但是,思考的開箱,並不禁止這樣可以使用裁判這一點。

class Parent extends Component { 
    onSomeThing() { 
    // Call some method of myChild 
    this.myChild.myChildsPublicMethod() 
    } 

    render() { 
    return <MyChild ref={ref => { this.myChild = ref; }} /> 
    } 
} 

// MyChild 
// Just as demo using Pure components here. 
// You could use the normal class notation.. 
const MyChild =() => <div>Ola</div>; 
MyChild.someMethod =() => console.log('Ola'); 

這裏更多https://zhenyong.github.io/react/docs/more-about-refs.html