[英]Failed prop type while doing prop validation in React.js
我正在開發一個 React 項目,其中有一個名為CurrencyContext.js
的上下文。 整個項目運行良好,但是,我收到一個控制台錯誤,顯示Failed prop type
。
完整的錯誤信息
警告:失敗的道具類型:CurrencyContextProvider:道具類型
children
無效; 它必須是 function,通常來自prop-types
package,但收到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;
React.ReactNode
在 javascript 中undefined
。 如果您使用的是 typescript 它將是一個類型,但即使它只存在於編譯時並且不能用於 propTypes。
相反,做 children 道具類型的方法是:
import PropTypes from 'prop-types';
// ...
CurrencyContextProvider.propTypes = {
children: PropTypes.node
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.