简体   繁体   English

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

[英]Setting defaultProps on functional component in React

I have a bunch of functional react UI components. 我有一堆功能化的UI组件。 I want to set defaultProps to those components. 我想将defaultProps设置为这些组件。 However, it seems that my components do not apply those default props. 但是,看来我的组件没有应用那些默认道具。 Here is an example code: 这是示例代码:

// @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

The result that I get is CSS class c-label--undefined . 我得到的结果是CSS类c-label--undefined If I pass default values during object destructuring, const { type = 'narrow' } it works fine. 如果我在对象分解过程中传递了默认值,则const { type = 'narrow' }可以正常工作。 The above code works also when I convert functional component to a class-based component. 当我将功能组件转换为基于类的组件时,以上代码也适用。

I have researched this issue a lot but I haven't been able to find a solution. 我对此问题进行了很多研究,但找不到解决方案。 Of course, I could pass the default values during destructuring but it is harder to read and my company would like to adopt the pattern that I have described. 当然,我可以在销毁过程中传递默认值,但是很难理解,我的公司希望采用我所描述的模式。 I've seen some articles describing that it is possible to pass defaultProps to functional components but perhaps that has changed? 我看过一些文章,描述了可以将defaultProps传递给功能组件,但是也许已经改变了吗? I would appreciate any suggestions. 我将不胜感激任何建议。

I'm pretty sure your code should work. 我很确定您的代码可以正常工作。 Just checked it out on my own. 只是自己检查了一下。 type has the default value if not passed as a prop. 如果未作为prop传递,则type具有默认值。 Maybe the issue is from where you're using the component? 也许问题出在您使用组件的地方?

OK, so after some research it appears that defaultProps do not work in this setting because of react on rails. 好的,因此经过研究后,由于对rails的反应,defaultProps在此设置中似乎无法使用。 We use that for server side rendering. 我们将其用于服务器端渲染。 Hopefully this will be helpful to those who might be in a similar situation 希望这会对那些处于类似情况的人有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM