Call a React component method from outside

前端 未结 11 1465
灰色年华
灰色年华 2020-11-28 04:56

I want to call a method exposed by a React component from the instance of a React Element.

For example, in this jsfiddle. I want to call the alertMessage

相关标签:
11条回答
  • 2020-11-28 04:59

    If you are in ES6 just use the "static" keyword on your method from your example would be the following: static alertMessage: function() { ...
    },

    Hope can help anyone out there :)

    0 讨论(0)
  • 2020-11-28 05:01

    method 1 using ChildRef:

    public childRef: any = React.createRef<Hello>();
    
    public onButtonClick= () => {
        console.log(this.childRef.current); // this will have your child reference
    }
    
    <Hello ref = { this.childRef }/>
    <button onclick="onButtonClick()">Click me!</button>
    

    Method 2: using window register

    public onButtonClick= () => {
        console.log(window.yourRef); // this will have your child reference
    }
    
    <Hello ref = { (ref) => {window.yourRef = ref} }/>`
    <button onclick="onButtonClick()">Click me!</button>
    
    0 讨论(0)
  • 2020-11-28 05:02

    I've done something like this:

    class Cow extends React.Component {
    
        constructor (props) {
            super(props);
            this.state = {text: 'hello'};
        }
    
        componentDidMount () {
            if (this.props.onMounted) {
                this.props.onMounted({
                    say: text => this.say(text)
                });
            }
        }
    
        render () {
            return (
                <pre>
                     ___________________
                    < {this.state.text} >
                     -------------------
                            \   ^__^
                             \  (oo)\_______
                                (__)\       )\/\
                                    ||----w |
                                    ||     ||
                </pre>
            );
        }
    
        say (text) {
            this.setState({text: text});
        }
    
    }
    

    And then somewhere else:

    class Pasture extends React.Component {
    
        render () {
            return (
                <div>
                    <Cow onMounted={callbacks => this.cowMounted(callbacks)} />
                    <button onClick={() => this.changeCow()} />
                </div>
            );
        }
    
        cowMounted (callbacks) {
            this.cowCallbacks = callbacks;
        }
    
        changeCow () {
            this.cowCallbacks.say('moo');
        }
    
    }
    

    I haven't tested this exact code, but this is along the lines of what I did in a project of mine and it works nicely :). Of course this is a bad example, you should just use props for this, but in my case the sub-component did an API call which I wanted to keep inside that component. In such a case this is a nice solution.

    0 讨论(0)
  • There are two ways to access an inner function. One, instance-level, like you want, another, static level.

    Instance

    You need to call the function on the return from React.render. See below.

    Static

    Take a look at ReactJS Statics. Note, however, that a static function cannot access instance-level data, so this would be undefined.

    var onButtonClick = function () {
        //call alertMessage method from the reference of a React Element! 
        HelloRendered.alertMessage();
        //call static alertMessage method from the reference of a React Class! 
        Hello.alertMessage();
        console.log("clicked!");
    }
    
    var Hello = React.createClass({
        displayName: 'Hello',
        statics: {
            alertMessage: function () {
                alert('static message');
            }
        },
        alertMessage: function () {
            alert(this.props.name);
        },
    
        render: function () {
            return React.createElement("div", null, "Hello ", this.props.name);
        }
    });
    
    var HelloElement = React.createElement(Hello, {
        name: "World"
    });
    
    var HelloRendered = React.render(HelloElement, document.getElementById('container'));
    

    Then do HelloRendered.alertMessage().

    0 讨论(0)
  • 2020-11-28 05:09

    With the render method potentially deprecating the returned value, the recommended approach is now to attach a callback ref to the root element. Like this:

    ReactDOM.render( <Hello name="World" ref={(element) => {window.helloComponent = element}}/>, document.getElementById('container'));
    

    which we can then access using window.helloComponent, and any of its methods can be accessed with window.helloComponent.METHOD.

    Here's a full example:

    var onButtonClick = function() {
      window.helloComponent.alertMessage();
    }
    
    class Hello extends React.Component {
      alertMessage() {
        alert(this.props.name);
      }
    
      render() {
        return React.createElement("div", null, "Hello ", this.props.name);
      }
    };
    
    ReactDOM.render( <Hello name="World" ref={(element) => {window.helloComponent = element}}/>, document.getElementById('container'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="container"></div>
    <button onclick="onButtonClick()">Click me!</button>

    0 讨论(0)
  • 2020-11-28 05:11

    You can just add an onClick handler to the div with the function (onClick is React's own implementation of onClick) and you can access the property within { } curly braces, and your alert message will appear.

    In case you wish to define static methods that can be called on the component class - you should use statics. Although:

    "Methods defined within this block are static, meaning that you can run them before any component instances are created, and the methods do not have access to the props or state of your components. If you want to check the value of props in a static method, have the caller pass in the props as an argument to the static method." (source)

    Some example code:

        const Hello = React.createClass({
    
            /*
                The statics object allows you to define static methods that can be called on the component class. For example:
            */
            statics: {
                customMethod: function(foo) {
                  return foo === 'bar';
                }
            },
    
    
            alertMessage: function() {
                alert(this.props.name);                             
            },
    
            render: function () {
                return (
                    <div onClick={this.alertMessage}>
                    Hello {this.props.name}
                    </div>
                );
            }
        });
    
        React.render(<Hello name={'aworld'} />, document.body);
    

    Hope this helps you a bit, because i don't know if I understood your question correctly, so correct me if i interpreted it wrong:)

    0 讨论(0)
提交回复
热议问题