简体   繁体   中英

Failed prop type while doing prop validation in React.js

I'm working on a React project, in which there is a context under the name of CurrencyContext.js . The whole project is running perfectly, however, I'm getting a console error that says Failed prop type .

Full error message

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 .

For more clarifications here is the code of CurrencyContext.js . Please let me know if something is not clear enough.

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 is undefined in javascript. If you're using typescript it would be a type, but even that only exists at compile time and cannot be used for propTypes.

Instead, the way to do the children prop type is:

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

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