首页 > 解决方案 > 在组件上自动传递道具

问题描述

我创建了一个Input使用 Styled Components 设置样式的组件。我现在将那个 Input 组件与Formik. 我希望能够自动设置onChange,onBlurvalueprops 而不是每次都设置它们(就像我使用 FormikField组件会发生什么)。

也就是说,现在这是我的组件在使用时的外观:

<Input
  name="firstName"
  onBlur={handleBlur}
  onChange={handleChange}
  value={values.firstName}
/>

我希望组件在使用时看起来像这样:

<Input name="firstName" />

然后,在幕后,onBlur将设置为handleBluronChange将设置为handleChangevalue并将设置为values.[name]。也就是name道具的价值。因此,在此示例中,它将设置为values.firstName. 如果nameprop 设置为lastName,则valueprop 将自动设置为values.lastName

知道我该怎么做吗?

注意:我知道FieldFormik 的道具可以做到这一点,但我想改用我的自定义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}
/>

标签: reactjsreact-propsreact-component

解决方案


我不认为这是个好主意。但是你可以做的是创建 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}
/>

但这确实是个坏主意。


推荐阅读