我正在尝试让redux-form与TypeScript和Styled-Components一起工作。在下面的代码示例中,为什么它不能与样式化的输入组件一起工作?输入呈现出来,但每个按键都失去了焦点。还需要单击两次来聚焦元素。看起来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);
是的,我终于想通了..我犯了一个错误,那就是在render方法中创建了样式化组件包装:
const StyledInput = styled.input`
background-color: deeppink;
;
显然,在render()中应用一个hoc-high-order组件是不安全的。因此当将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库的文档时弄清楚了这一点,这里有一个链接解释了在HOC上应用(任何)HOC:redux-auth-wrapper文档是安全的