【问题标题】:Failed prop type while doing prop validation in React.js在 React.js 中进行道具验证时道具类型失败
【发布时间】:2022-01-15 19:35:19
【问题描述】:

我正在开发一个 React 项目,其中有一个名为 CurrencyContext.js 的上下文。整个项目运行良好,但是,我收到一个控制台错误,上面写着Failed prop type

完整的错误信息

警告:失败的道具类型:CurrencyContextProvider:道具类型children无效;它必须是一个函数,通常来自prop-types 包,但收到了undefined。这通常是因为诸如PropTypes.function 而不是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;

【问题讨论】:

  • 尝试使用children: React.elementType
  • @LucaPizzini 没用

标签: javascript reactjs react-context


【解决方案1】:

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

相反,子类道具类型的做法是:

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

【讨论】:

    猜你喜欢
    • 2017-09-26
    • 2021-07-27
    • 2017-07-11
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 2019-12-18
    相关资源
    最近更新 更多