【问题标题】:Bind default props to component at render time在渲染时将默认道具绑定到组件
【发布时间】:2021-03-05 13:09:39
【问题描述】:

我很好奇 React 是否允许您在不属于您的组件上设置一些默认道具。

假设您有一个TextField 组件,并且您希望确保每次在此给定项目中使用 TextField 时,您都在传递 hasFloatingLabel={true} 属性。

我确信这段代码不会工作,但是,基本上是我想要做的:

import { TextField as CCTextField } from '@MyCompany/core-components'

export const TextField = CCTextField.bind({
  hasFloatingLabel: true
})

就像是,我对.bind 的一种特殊形式感兴趣,它允许默认一些“道具”,并将这些作为我自己的自定义默认值。

...理论上,这可以通过全局变量来实现,但这永远无法通过代码审查。 (function foo({bar = window.fooDefaults.bar}) {}

我认为一个简单的选择是创建一个“包装器”组件。

为了这个问题,假设我想要一个 1-3 行代码来在一个组件上设置几个默认道具。所以,你可以在任何渲染函数中做这样的事情:

import { TextField as CCTextField } from '@MyCo/core-components'

const FunctionalComponentFoo = ({a, b, c}) => {

  // ...calls a series of hooks...

  // Would this work??
  const TextField = (props) => CCTextField({
    hasFloatingLabel: true,
    placeholder: ' ',
    severalMoreFieldsA: a,
    severalMoreFieldsB: b,
    severalMoreFieldsC: c,
    id: 'idPrefix_' + props.name,
    ...props
  })

  // ...not really a simple component...

  return (
    <div className="one">
      <div className="two">
        <TextField name="firstName" />
      </div>
      <div className="three">
        <TextField name="lastName" />
      </div>
      <TextField name="address1" />
      <TextField name="address2" />
    </div>
    {/* ... many more fields ... */}
  )
}

正如你所想象的,在每个 TextField 中重复这些 props 会使组件变得很大+很长。

我也对使用道具传播不感兴趣({...defaultProps},因为它会在每个 &lt;TextField 调用中添加另一行。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    虽然听起来很有趣,但我不会走这条路。 相反,我会创建一个包装器元素,它将传递我想要的任何道具,并公开它。 如果您的项目组织良好,那应该不是问题。

    import { TextField as CCTextField } from '@MyCompany/core-components'
    
    export const TextField = props => <CCTextField hasFloatingLabel={true} {...props} />
    

    或者简单地通过定期将默认道具绑定到这个组件。

    【讨论】:

    • 应该将 {...props} 放在 hasFoatingLabel 之后,这样您仍然可以根据需要将其关闭?
    猜你喜欢
    • 2020-05-31
    • 2021-07-22
    • 1970-01-01
    • 2020-07-27
    • 2019-07-26
    • 2021-07-13
    • 1970-01-01
    • 2018-04-03
    • 2019-04-19
    相关资源
    最近更新 更多