我创建了一个Input
组件,该组件已使用样式化组件进行样式设置。我现在将Formik
与该Input组件一起使用。我希望能够自动设置onChange
,onBlur
和value
道具,而不必每次都设置它们(例如,如果我使用Formik {{ 1}}组件)。
也就是说,现在这是我的组件在使用时的外观:
Field
我希望组件在使用时看起来像这样:
<Input
name="firstName"
onBlur={handleBlur}
onChange={handleChange}
value={values.firstName}
/>
然后,在后台将<Input name="firstName" />
设置为onBlur
,将handleBlur
设置为onChange
,将handleChange
设置为{{ 1}}。也就是说,为value
道具的价值。因此,在此示例中,它将被设置为values.[name]
。如果将name
属性设置为values.firstName
,则name
属性将自动设置为lastName
。
你知道我该怎么做吗?
注意::我知道Formik的value
道具可以做到这一点,但是我想改用我的自定义values.lastName
组件。
更新
这里有一些其他代码可能与回答这个问题有关。
输入组件
Field
InputContent组件
Input
带有表格的Formik
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>
)
}
答案 0 :(得分:0)
我认为这不是一个好主意。但是您可以做的是创建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}
/>
但这确实是不好的想法。