gpt4 book ai didi

javascript - 在 React 中的功能组件上设置 defaultProps

转载 作者:行者123 更新时间:2023-12-03 03:47:50 29 4
gpt4 key购买 nike

我有一堆功能性的 React UI 组件。我想为这些组件设置defaultProps。但是,我的组件似乎不应用这些默认 Prop 。下面是一个示例代码:

// @flow
import React from 'react'
import classNames from 'classnames/bind'

type LabelType = 'default' | 'narrow' | 'wide'

const Label = (
props: {
text: string,
type: LabelType,
}
) => {
const { text, type } = props
const labelClass = classNames(
'c-label',
`c-label--${type}`
)

return (
<div className={labelClass}>
{text}
</div>
)
}

Label.defaultProps = {
type: 'narrow',
}

export default Label

我得到的结果是CSS类c-label--undefined。如果我在对象解构期间传递默认值,const { type = 'narrow' } 它工作正常。当我将功能组件转换为基于类的组件时,上面的代码也有效。

我对这个问题进行了很多研究,但一直未能找到解决方案。当然,我可以在解构过程中传递默认值,但它更难阅读,我的公司希望采用我所描述的模式。我看过一些文章描述可以将 defaultProps 传递给功能组件,但也许这已经改变了?我将不胜感激任何建议。

最佳答案

我很确定你的代码应该可以工作。刚刚自己查了一下。如果没有作为 prop 传递,则 type 具有默认值。也许问题出在您使用该组件的位置?

关于javascript - 在 React 中的功能组件上设置 defaultProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45297518/

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