从子级调用回调函数时,React-props为空

React - props is empty when calling a callback function from child

本文关键字:React-props 为空 函数 回调 调用      更新时间:2023-09-26

我的主组件上有一个按钮,当它被点击时,会打开一个"审批面板",当点击OK时,我会调用主组件的回调函数并执行一些逻辑。

我想传递回调函数(我的原因),问题是当调用回调函数时,props和state是未定义的。

为什么会发生这种情况?如果缺少任何信息,请告诉我。

我在这里添加了一个部分代码:

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}/>;
        ...
    }
}

尝试这些更改

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}/>;
        ...
    }
}

我认为您需要对React组件进行一些更改。

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

第二::将currentActionConfig定义为一个状态,并尝试将其用作this.state.currentActionConfig

第三个:指定onCommandApprovalOkClicked()上的绑定。像CCD_ 5和用于其它功能的类似物。

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}/>;
        ...
    }
}

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