在 React.js 中进行道具验证时道具类型失败

Failed prop type while doing prop validation in React.js

我正在做一个 React 项目,其中有一个名为 CurrencyContext.js 的上下文。整个项目 运行 完美,但是,我收到一个控制台错误,显示 Failed prop type.

完整的错误信息

Warning: Failed prop type: CurrencyContextProvider: prop type children is invalid; it must be a function, usually from the prop-types package, but received undefined.This often happens because of typos such as PropTypes.function instead of PropTypes.func.

更多说明请见CurrencyContext.js的代码。如果有什么地方不够清楚,请告诉我。

import React, {Component, createContext} from "react"

export const CurrencyContext = createContext()

class CurrencyContextProvider extends Component {

    constructor(props) {
        super(props);
        this.state = {
            selectedCurrency: 'USD'
        }
    }

    setCurrency(c){
        this.setState({selectedCurrency: c})
    }

    render() {
        return (
            <CurrencyContext.Provider value={{...this.state, setCurrency: this.setCurrency.bind(this)}}>
                {this.props.children}
            </CurrencyContext.Provider>
        )
    }
}

CurrencyContextProvider.propTypes = {
    children: React.ReactNode
}

export default CurrencyContextProvider;

React.ReactNode 是 javascript 中的 undefined。如果您使用的是打字稿,它将是一种类型,但即使它只存在于编译时,也不能用于 propTypes。

相反,处理子属性类型的方法是:

import PropTypes from 'prop-types';
// ...
CurrencyContextProvider.propTypes = {
    children: PropTypes.node
}