React - Call parent method in child component

后端 未结 2 1615
南旧
南旧 2020-11-30 10:49

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 exte         


        
2条回答
  •  無奈伤痛
    2020-11-30 11:19

    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() {
              
    Hello Child
    } } class Parent extends React.Component { constructor(props) { super(props); }; someMethod() { console.log('bar'); } render() { Hello Parent, {this.props.children} } }

提交回复
热议问题