简体   繁体   中英

ReactJS - Props.children changed but component not re-render

Currently, I have 2 class about container wrapper for render content as a child. It working only when I use styled component like containerEz class but not in BaseTemplateContainer class

If I want to fix class BaseTemplateContainer to re-render when this.props.children change, How to do it?

class containerEz It re-render when children prop was change

const ContainerEz = ({children}) => {

    const Wrapper = styled.div`
        padding: 0 20px;
        width: 100%;
        @media (min-width: 768px) {
            padding: 0 60px;
        }
    `;

    return (
        <Wrapper>
            {children}
        </Wrapper>
    );
}

export default ContainerEz;

class BaseTemplateContainer It's not re-render when children prop was change

class BaseTemplateContainer extends Component {
    state = {

    }

    render() {
        return (
            <div>
                {this.props.children}
            </div>
        );
    }
}

export default BaseTemplateContainer;

firstly your styled component should live outside the component like so

const Wrapper = styled.div`
    padding: 0 20px;
    width: 100%;
    @media (min-width: 768px) {
        padding: 0 60px;
    }
`;

const ContainerEz = ({children}) => {

    return (
        <Wrapper>
            {children}
          <BaseTemplateContainer children={children} /> call this inside here
        </Wrapper>
    );
}

export default ContainerEz;

then pass down the children to BaseTemplateContainer and when it rerenders with different props, they will display

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