简体   繁体   中英

How to re-render parent component from child component

parent component has ap tag which animate it's inner text. animation works when i refresh the page.

here is the Parent component:

import React, { Component } from 'react';
import Child from './Child';

class Parent extends Component {
    rerender=()=>{
        this.forceUpdate()
    }
    render() {
        return (
            <div>
                <p className='animate-left'>Animation</p>
                <Child rerender={this.rerender}/>
            </div>
        );
    }
}

export default Parent;

here is the Child component:

import React, { Component } from 'react';

class Child extends Component {
    clickHandler=()=>{
        this.props.rerender()
    }
    render() {
        return (
            <div>
                <button onClick={this.clickHandler}>Click</button>
            </div>
        );
    }
}

export default Child;

i want to animate again/ re-render parent component by clicking the button of child component. How to do that?

You have to have state in the parent component and pass down this state to the child component:

 import React, { Component } from "react"; import Child from "./Child"; class Parent extends Component { constructor(props) { super(props); this.state = { counter: 0 }; } rerender = () => { this.forceUpdate(); }; forceUpdate = () => { this.setState((state) => ({ counter: state.counter + 1 })); }; render() { console.log("got rendered"); return ( <div> <p className="animate-left" key={this.state.counter}>Animation</p> <Child rerender={this.rerender} /> </div> ); } } export default Parent;

and in the child component update this state:

 import React, { Component } from "react"; class Child extends Component { clickHandler = () => { this.props.rerender(); }; render() { return ( <div> <button onClick={this.clickHandler}>Click</button> </div> ); } } export default Child;

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