Call a React component method from outside

前端 未结 11 1543
灰色年华
灰色年华 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: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 (
                
                     ___________________
                    < {this.state.text} >
                     -------------------
                            \   ^__^
                             \  (oo)\_______
                                (__)\       )\/\
                                    ||----w |
                                    ||     ||
                
    ); } say (text) { this.setState({text: text}); } }

    And then somewhere else:

    class Pasture extends React.Component {
    
        render () {
            return (
                
    this.cowMounted(callbacks)} />
    ); } 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.

提交回复
热议问题