Call a React component method from outside

前端 未结 11 1574
灰色年华
灰色年华 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 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 (
                    
    Hello {this.props.name}
    ); } }); React.render(, 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:)

提交回复
热议问题