ReactJS - Call One Component Method From Another Component

前端 未结 2 2014
谎友^
谎友^ 2020-12-08 09:38

I have two components. I want to call a method of the first component from the second component. How can I do it?

Here is my code.

First Component

相关标签:
2条回答
  • 2020-12-08 10:02

    Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

    Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

    • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
    • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
    • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

    UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

    let counter = 0;
    function handleInstantiate() {
       counter++;
    }
    
    constructor(props) {
       super(props);
       handleInstantiate();
    }
    
    0 讨论(0)
  • 2020-12-08 10:18

    You can do something like this

    import React from 'react';
    
    class Header extends React.Component {
    
    constructor() {
        super();
    }
    
    checkClick(e, notyId) {
        alert(notyId);
    }
    
    render() {
        return (
            <PopupOver func ={this.checkClick } />
        )
    }
    };
    
    class PopupOver extends React.Component {
    
    constructor(props) {
        super(props);
        this.props.func(this, 1234);
    }
    
    render() {
        return (
            <div className="displayinline col-md-12 ">
                Hello
            </div>
        );
    }
    }
    
    export default Header;
    

    Using statics

    var MyComponent = React.createClass({
     statics: {
     customMethod: function(foo) {
      return foo === 'bar';
      }
     },
       render: function() {
     }
    });
    
    MyComponent.customMethod('bar');  // true
    
    0 讨论(0)
提交回复
热议问题