反应子组件未在父更新上更新

时间:2020-03-24 11:48:50

标签: reactjs

我有一个带有多个标签的标签面板。在渲染时,将正确调整选项卡内容的大小以填满选项卡面板的高度。调整浏览器大小时,父选项卡面板的高度会更新,但选项卡内容不会更新其高度。有想法吗?

export class MultiTabs extends React.Component {
constructor(props) {
    super(props);

    this.tabBarHeight = 44;
}

render() {
    return(
        <>
            <TabPanel
                height={this.props.height}
            >
                <Container title='Personnels'>
                    <Personnel
                        height={this.props.height - this.tabBarHeight}
                    />
                </Container>

                <Container title='Files'>
                    <Files
                        height={this.props.height - this.tabBarHeight}
                    />
                </Container>

                <Container title='Hello World!' scrollable={true}>
                    <Hello/>
                </Container>
            </TabPanel>
        </>
    );
}

我尝试使用状态。这是使用状态的稍微不同的修改。调整浏览器大小时,innerTabHeight会更改,但选项卡内容保持不变。

export class MultiTabs extends React.Component {
    constructor(props) {
        super(props);

        this.tabBarHeight = 44;

        this.state = {
            innerTabHeight: props.height - this.tabBarHeight
        }
    }

    render() {
        return(
            <>
                <TabPanel
                    height={this.props.height}
                >
                    <Container title='Personnels'>
                        <Personnel
                            height={this.state.innerTabHeight}
                        />
                    </Container>

                    <Container title='Files'>
                        <Files
                            height={this.state.innerTabHeight}
                        />
                    </Container>

                    <Container title='Hello World!' scrollable={true}>
                        <Hello/>
                    </Container>
                </TabPanel>
            </>
        );
    }

    componentDidUpdate(prevProps) {
        if(prevProps.height !== this.props.height) {
            this.setState({
                innerTabHeight: this.props.height - this.tabBarHeight
            })
        }
    }
}

0 个答案:

没有答案