如何使 redux-form 与 TypeScript 和样式组件一起工作?

How to make redux-form work with TypeScript and styled-components?

我正在尝试让 redux-form 与 TypeScript 和样式组件一起使用。在下面的代码示例中,为什么它不能与样式化的输入组件一起使用?输入呈现,但焦点在每次按键时丢失。还需要单击两次才能聚焦元素。似乎 redux-form 试图控制从 styled-components 返回的包装元素? redux-form 和 styled-components 都使用 HOC - 高阶组件将道具传递给底层元素。

export interface ITxtProps extends WrappedFieldProps {
  label?: string;
}

export const FieldHack = class extends Field<any> {};

const renderTxt = (props: ITxtProps & GenericFieldHTMLAttributes) => {
  const StyledInput = styled.input`
    background-color: deeppink;
  `;
  const notWorking = <StyledInput {...props.input} />;
  const worksPerfectly = <input {...props.input} />;
  return (
  <div>
    <div>{props.label}</div>
    {notWorking}
  </div>
);
}

const NormalLoginComponent = (props: {
  handleSubmit?: SubmitHandler<{}, {}>;
}) => {
  const { handleSubmit } = props;
  return (
    <form onSubmit={handleSubmit}>
      {/* this does not work when using styled components: */}
      <Field name={'email'} component={renderTxt}  />

      {/* this gives an error, property label does not exist on type... */}
      {/*<Field name={'email'} component={renderTxt} label="email" />*/}

      {/* this works, but no intellisense/static types */}
      <FieldHack name={'email2'} component={renderTxt} label="email" />

      <Field name={'password'} component={'input'} type="password" />
      <Button text={'log in'} onClick={handleSubmit} />
    </form>
  );
};

export interface ILoginForm {
  email: string;
  password: string;
}

const LoginForm = reduxForm<Readonly<ILoginForm>, {}>({
  form: 'loginNormal',
})(NormalLoginComponent);

是的,我终于想通了。我犯了一个错误,那就是在渲染方法中创建我的样式组件包装器:

const StyledInput = styled.input`
  background-color: deeppink;
;

显然在 render() 中应用 HOC - 高阶组件是不安全的。所以它应该在将 HOC 移出渲染时起作用:

export interface ITxtProps extends WrappedFieldProps {
  label?: string;
}

export const FieldHack = class extends Field<any> {};

// wrap you HOC outside render:
const StyledInput = styled.input`
    background-color: deeppink;
  `;

const renderTxt = (props: ITxtProps & GenericFieldHTMLAttributes) => {
  // works now :)
  const notWorking = <StyledInput {...props.input} />;
  const worksPerfectly = <input {...props.input} />;
  return (
  <div>
    <div>{props.label}</div>
    {notWorking}
  </div>
);
}

我正在阅读另一个 HOC 库的文档来解决这个问题,这里有一个 link 解释了在哪里可以安全地应用(任何)HOC:redux-auth-wrapper documentation on HOCs