简体   繁体   中英

Accessing this.props function in react ComponentDidMount

I am trying to access parent function (passed as property to child) in child's componentDidMount() but it is showing as undefined.

constructor(props) {
    super(props)
    this.actionis = this.props.actionis.bind(this);
}

componentDidMount(){
    this.actionis(selectednow, 'disabled');
}

EDIT: Parent Constructor:

constructor(props) {
        super(props)
        var abc = "";
        this.handlerHeading = this.handlerHeading.bind(this)
        this.handlerHeadingRemove = this.handlerHeadingRemove.bind(this)
     }

Parent Render():

<Mappingcomp actionis={this.handlerHeading} />

handlerHeading Function:

handlerHeading(index, disabled) {
        xarraydis.push(index);
    }

Error Is:

this.actionis is not a function

But i can access it in render() function and not in componentDidMount() .

You don't need to bind a prop callback function.

Just do

componentDidMount(){
    // don't forget to define selectednow
    this.props.actionis(selectednow, 'disabled');
}

You just need to bind the returned arguments in the parent with the function like

<Mappingcomp actionis={(index, disabled) => this.handlerHeading(index, disabled)} />

and then in the child use

constructor(props) {
    super(props)
}

componentDidMount(){
    this.props.actionis(selectednow, 'disabled');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM