简体   繁体   中英

react calling a function in a child component

Im trying to call a function that is stored in a child component form the parent. But not sure to to do it. I know if were form child to parent I could simply use the component props but not sure how to do it from parent to child.

as you can see form the below example the button in the parent class need to trigger the display function in the child class.

var Parent = React.createClass ({
   render() {
       <Button onClick={child.display} ?>
   } 
})


var Child = React.createClass ({
    getInitialState () {
        return {
            display: true
        };
    },


    display: function(){
        this.setState({
             display: !this.state.display
        })
    },

    render() {
     {this.state.display}
    } 
})

The easiest way to achieve this is through using refs (See documentation ).

var Parent = React.createClass ({

   triggerChildDisplay: function() {
       this.refs.child.display();
   },

   render() {
       <Button onClick={this.triggerChildDisplay} />
   } 
})


var Child = React.createClass ({
    getInitialState () {
        return {
            display: true
        };
    },


    display: function(){
        this.setState({
             display: !this.state.display
        })
    },

    render() {
     {this.state.display}
    } 
})

I basically copied in your example, but do note that in your Parent, I don't see you render a Child component, but typically, you would, and on that Child you would give it a ref, like <Child ref="child" /> .

I don't believe it is possible to call a child function from a parent component.

For this use case there is a better way to achieve this result and that is by setting the 'display' property of the child component to the value of a prop passed to it by the parent, eg.

var Parent = React.createClass ({
    getInitialState() {
        return {displayChild: false};
    },

    toggleChildDisplay() {
        this.setState({
            displayChild: !this.state.displayChild
        });
    },

    render() {
        <Button onClick={this.toggleChildDisplay} />
        <Child display={this.state.displayChild} />
    }
});

var Child = React.createClass ({
    render: function() {
        if (this.props.display) {
            /*return component*/
        } else {
            /*Don't render*/
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM