首页 > 解决方案 > TypeError:无法读取 null 的属性“withFooter”

问题描述

我正在尝试在反应打字稿中创建一个布局元素。我试图有一个布尔道具来确定是否渲染页脚。不幸的是,我得到了一个无法读取未定义问题的属性。我还想为 prop 类型设置一个默认的 true 值。我是新来的反应,但仍在努力学习细节。

import React, { Component } from 'react'
import Scrollbar from 'react-smooth-scrollbar'
import Header from '../Header/index'
import Footer from '../Footer/index'

type Props = {
    withFooter: boolean
}

class Layout extends Component<{}, Props> {
    render() {
        let footer
        if (this.state.withFooter) {
            footer = <Footer />
        } else {
            footer = null
        }

        return (
            <div>
                <Scrollbar>
                    <Header />
                    {this.props.children}
                    {footer}
                </Scrollbar>
            </div>
        );
    }
}

export default Layout

标签: reactjstypescriptreact-props

解决方案


你能试试这个

type Props = {
    withFooter: boolean
}

class Layout extends Component<Props, {}> {
    public static defaultProps = {
         withFooter: true,
    };
    render() {
        let footer
        if (this.props.withFooter) {
            footer = <Footer />
        } else {
            footer = null
        }

        return (
            <div>
                <Scrollbar>
                    <Header />
                    {this.props.children}
                    {footer}
                </Scrollbar>
            </div>
        );
    }
}

推荐阅读