gpt4 book ai didi

javascript - 使用 ESLint react PropType

转载 作者:行者123 更新时间:2023-11-30 06:12:37 27 4
gpt4 key购买 nike

开始使用 ESLint 并遇到 PropType 的几个问题,目前我有一个 Prop children,现在让我们假设这个 Prop 是一个 string。我收到错误消息 'children' is missing in props validationeslint(react/prop-types),为了解决这个问题,我只是使用 PropTypes,如下所示:

CartProvider.propTypes = {
children: PropTypes.string,
}

上面解决了这个问题然后我又遇到了另一个问题

为了解决这个问题,我添加了另一个 PropType,如下所示:

CartProvider.defaultProps = {
children: PropTypes.string,
}

所以我的理解是,每次我使用 Prop 时,我都需要使用propTypedefaultProps。好的,这解决了基于 string 的 prop 的问题。但实际上这个 Prop 是一个 array 然后 array 我遇到了其他问题 Prop typearrayis forbonedeslint(react/forbid - Prop 类型)

请帮助我理解为什么 ESLint 将这些 Prop 标记为错误,我知道如何禁用它,但我想了解它发生的原因,然后编写更好的代码。

这是一个示例项目:

CartContext

import React from 'react'
import PropTypes from 'prop-types'

export const CartContext = React.createContext(null)

export const CartProvider = ({ children }) => {
const [cartTotal, setCartTotal] = React.useState(0)
const incrementCartTotal = () => setCartTotal(cartTotal + 1)

return (
<CartContext.Provider
value={{
cartTotal,
incrementCartTotal,
}}
>
{children}
</CartContext.Provider>
)
}

CartProvider.propTypes = {
children: PropTypes.string,
}

CartProvider.defaultProps = {
children: PropTypes.string,
}

应用

import React from 'react'
import { CartContext, CartProvider } from './CartContext'

function CartTotalItems() {
const { cartTotal } = React.useContext(CartContext)
return (
<p>
Total items currently in cart:
{cartTotal}
</p>
)
}

function AddToCart() {
const { incrementCartTotal } = React.useContext(CartContext)
return (
<button type="button" onClick={incrementCartTotal}>
Add to cart
</button>
)
}

export default function App() {
return (
<CartProvider>
<CartTotalItems />
<AddToCart />
</CartProvider>
)
}

更新这对我有用,删除 2 PropTypes 并添加:

CartProvider.propTypes = {
children: PropTypes.node.isRequired,
}

最佳答案

您误会了 type of children并混淆了 use of defaultProps :

// Use for initial value
CartProvider.defaultProps = {
counter: 10,

/*
You declared the initial value to be the value of `PropTypes.string`
children: PropTypes.string
*/
}
// Children are always an Array of `ReactElement`/ `ReactElement` node.
CartProvider.propTypes = {
counter: PropTypes.number,

children: PropTypes.node.isRequired,

/* Same
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]).isRequired
*/

/*
props.children can't be a string.
children: PropTypes.string,
*/
}

关于javascript - 使用 ESLint react PropType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57989644/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com