2016-07-18 26 views
0

我在主组件上有一个按钮,当它点击它时打开“Approval pannel”,并且当单击OK时,我正在调用一个回调函数组件并执行一些逻辑。React - 当从子组件调用回调函数时,道具是空的

我想通过回调函数(我的理由),问题是当回调函数被调用时,道具和状态都是未定义的。

这是为什么发生?如果有任何信息丢失,请告诉我。

我加入这里的部分代码:

class MainComponent extends React.Component { 
    constructor(props){ 
     currentActionConfig = {onOkClick: this.onGenericApprovalOkClicked, ...}; 
    } 

    onCommandApprovalOkClicked(commandText){ 
     console.log(this.props); <- 'undefined' 
    } 

    render(){ 
     return <ActionsApprovalPanel currentActionConfig={this.currentActionConfig}/> 
    } 
} 


export default class ActionsApprovalPanel extends React.Component { 
    render() 
    { 
     ... 
     return <ChangeIpApproval onOkClick={this.props.currentActionConfig.onOkClick}/>; 
     ... 
    } 
} 

回答

0

我想你需要让你的阵营组件一些变化。

第一张:在构造函数中调用super()

二::定义currentActionConfig的状态,并尝试使用它作为this.state.currentActionConfig

:指定onCommandApprovalOkClicked()的结合。如 onCommandApprovalOkClicked = (commandText) => {}和其他功能类似。

class MainComponent extends React.Component { 
    constructor(props){ 
     super(props); 
     this.state = { 
     currentActionConfig = {onOkClick: this.onGenericApprovalOkClicked, ...} 
     }; 
    } 

    onCommandApprovalOkClicked(commandText){ 
     console.log(this.props); <- 'undefined' 
    } 

    render(){ 
     return <ActionsApprovalPanel currentActionConfig={this.state.currentActionConfig}/> 
    } 
} 


export default class ActionsApprovalPanel extends React.Component { 

    render() 
    { 
     ... 
     return <ChangeIpApproval onOkClick={this.props.currentActionConfig.onOkClick}/>; 
     ... 
    } 
} 

进行这些更改并查看它们是否有效。

0

尝试这些变化

class MainComponent extends React.Component { 
    constructor(props){ 
     super(props); //1. Call super 
     this.currentActionConfig = {onOkClick: this.onGenericApprovalOkClicked.bind(this), ...}; // 2.bind this 
    } 

    onCommandApprovalOkClicked(commandText){ 
     console.log(this.props); <- 'undefined' 
    } 

    render(){ 
     return <ActionsApprovalPanel currentActionConfig={this.currentActionConfig}/> 
    } 
} 


export default class ActionsApprovalPanel extends React.Component { 
    render() 
    { 
     ... 
     return <ChangeIpApproval onOkClick={this.props.currentActionConfig.onOkClick}/>; 
     ... 
    } 
} 
相关问题