2017-07-27 77 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