reactjs - 在组件上自动传递道具
问题描述
我创建了一个Input
使用 Styled Components 设置样式的组件。我现在将那个 Input 组件与Formik
. 我希望能够自动设置onChange
,onBlur
和value
props 而不是每次都设置它们(就像我使用 FormikField
组件会发生什么)。
也就是说,现在这是我的组件在使用时的外观:
<Input
name="firstName"
onBlur={handleBlur}
onChange={handleChange}
value={values.firstName}
/>
我希望组件在使用时看起来像这样:
<Input name="firstName" />
然后,在幕后,onBlur
将设置为handleBlur
,onChange
将设置为handleChange
,value
并将设置为values.[name]
。也就是name
道具的价值。因此,在此示例中,它将设置为values.firstName
. 如果name
prop 设置为lastName
,则value
prop 将自动设置为values.lastName
。
知道我该怎么做吗?
注意:我知道Field
Formik 的道具可以做到这一点,但我想改用我的自定义Input
组件。
更新
这是一些可能与回答此问题相关的其他代码。
输入组件
export const Input = props => {
const {
forId,
name,
placeholder,
} = props
const titleCase = startCase(name)
return (
<InputBase {...props}>
<InputSection>
<InputContent
id={forId ? forId : name}
placeholder={placeholder ? placeholder : titleCase}
type="text"
{...props}
/>
</InputSection>
</InputBase>
)
}
输入内容组件
export const InputContent = styled.input`
// STYLES
`
Formik 与 Form
<Formik
render={props => {
const {
handleBlur,
handleChange,
values,
} = props
return (
<Form>
<Input
name="firstName"
onBlur={handleBlur}
onChange={handleChange}
value={values.firstName}
/>
<Button type="submit">Submit</Button>
</Form>
)
}}
initialValues={{firstName: ''}
validationSchema={validationSchema}
/>
解决方案
我不认为这是个好主意。但是你可以做的是创建 HOC 并包装它
// lasyWrapper.js
export function lazyWrapper(Input) {
return LazyWrapper extends React.Component {
render() {
return (
<Input
{...this.props}
name={this.props.name}
onBlur={this.props.handleBlur}
onChange={this.props.handleChange}
value={this.props.values[this.props.name]}
/>
)
}
}
}
// Input.js
export default lazyWrapper(Input)
// use somewhere
<Input
name="firstName"
{...this}
/>
但这确实是个坏主意。
推荐阅读
- youtube - 如何创建基于章节的 YouTube 播放列表,如“The Coding Train”?
- python - 如何使用 sinc 函数为信号创建低通滤波器/高通滤波器,其中信号 x 给定,参数 alpha <1 和 beta>1 在 python
- excel - C# VSTO Add-in Excel:这个 Excel Super-Tab 控件的名称是什么以及如何制作它?(上下文选项卡或工具选项卡)
- mongodb - 如何将模型从文档列表更新为mongodb中的数组
- postgresql - 从数据工厂读取 Postgress(以 SQL_ASCII 编码)
- cookies - 如何在我的扩展程序中获取带有凭据的 URL,而不会将 cookie 泄漏到用户 cookie 存储?
- python-3.x - 如何将数据附加到for循环中的空列表?
- methods - 在输入中输入数据
- sql - django get_next_by_FOO() 查询是如何工作的?
- android - WebView 显示消息“抱歉有错误”