Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

javascript - React - Call parent method in child component

I have a parent and child compoents and I want to call a parent method in the child component like this:

import Parent from './parent.js';
class Child extends React.Component {
    constructor(props) {
        super(props);
        };

    click() {
        Parent.someMethod();
    }

    render() {
          <div>Hello Child onClick={this.click}</>
    }
}

class Parent extends React.Component {
    constructor(props) {
        super(props);
        };

    someMethod() {
        console.log('bar');
    }

    render() {
          <div>Hello Parent</>
    }
}

This returns an error message:

Uncaught TypeError: _Parent2.default.someMethod is not a function

How can this parent method be called in the child component?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this. Passing the function down as props to the child component.

import Parent from './parent.js';
class Child extends React.Component {
    constructor(props) {
        super(props);
        };

    click = () => {
        this.props.parentMethod();
    }

    render() {
          <div onClick={this.click}>Hello Child</div>
    }
}

class Parent extends React.Component {
    constructor(props) {
        super(props);
        };

    someMethod() {
        console.log('bar');
    }

    render() {
          <Child parentMethod={this.someMethod}>Hello Parent, {this.props.children}</Child>
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...