2017-07-27 85 views
0

我與報關文件有一個類,本地進口函數:陣營從出口

export default class ParticipantRow extends Component 

在這一類我有,我想在另一個類導入功能。 反正有,我可以從類中導入一個函數,就像我的例子一樣,如果是這樣,怎麼樣?

我要導入的功能已經被綁定到ParticipantRow類的構造函數。我想使用此功能作爲另一個類的事件處理程序,如果我簡單地聲明ParticipantRow.handlePressParticipant()作爲另一個類的事件處理程序,導入ParticipantRow後,我得到以下錯誤:「未定義是不是一個函數(計算」 _ParticipantRow2.default.handlePressParticipant())」

在前進,謝謝。

+0

你可以只導入了全班同學'從」 ./ParticipantRow.js'進口ParticipantRow;',比運行ParticipantRow.someMethod() –

+0

我migh不是已經足夠精確,我如果是這樣,道歉。 我希望導入的函數已綁定到ParticipantRow類的構造函數。我想使用此功能作爲另一個類的事件處理程序,如果我簡單地聲明ParticipantRow.handlePressParticipant()作爲另一個類的事件處理程序,導入ParticipantRow我收到以下錯誤後:「未定義是不是(評估函數」 _ParticipantRow2 .default.handlePressParticipant())' – Refi

+1

如果你想使用它作爲一個事件處理函數,嘗試在無() 中傳遞ParticipantRow.handlePressParticipant。如果你提供來自這兩個類的代碼示例,將會更容易理解! –

回答

0

ParticipantRow是使用類中定義的反應成分,我認爲它有不同的方法,你想將它傳遞給另一個組件(我們稱爲OtherComponent)用作事件處理程序。您可以使用道具將ParticipantRow的成員函數傳遞給OtherComponent。

class ParticipantRow extends Component { 
    constructor(props) { 
    super(props); 
    // we need to bind this before we pass it to OtherComponent 
    this.handleEvent = this.handleEvent.bind(this); 
    } 
    handleEvent(e) { 
    // do something here 
    } 
    // In here we pass handleEvent to OtherComponent 
    render() { 
    return <OtherComponent handleEvent={this.handleEvent} /> 
    } 
} 

class OtherComponent extends Component { 
    constructor(props) { 
    super(props); 
    } 
    render() { 
    return <button onPress={this.props.handleEvent} /> 
    } 
} 

請大家注意,在這個例子中OtherComponent是ParticipantRow的孩子,因此它是確定從父(ParticipantRow)兒童(OtherComponent)傳球方法,但如果你有不同的要求,讓我們假設你想通過從ParticipantRow的方法到另一個組件,它是不是該組件的孩子,那麼你將有更多的工作要做,因爲在這種情況下,你需要手動添加事件系統,或者你可能想看看終極版。

進一步參考 https://react-cn.github.io/react/tips/communicate-between-components.html