【发布时间】: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},因为它会在每个 <TextField 调用中添加另一行。
【问题讨论】:
标签: javascript reactjs