我试图让redux-form与TypeScript和样式组件一起使用。在下面的代码示例中,为什么它不适用于样式化输入组件?输入呈现,但每次按键都会丢失焦点。它也需要两次点击来聚焦元素。似乎redux-form试图控制从样式组件返回的包装元素? redux-forms和styled-components都使用HOC - 高阶组件将props传递给底层元素。
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);
答案 0 :(得分:1)
是的,我终于想通了..我犯了一个错误,那就是在render方法中创建我的样式组件包装器:
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图书馆的文档时,这里有一个链接,解释了应用(任何)HOC的安全性:redux-auth-wrapper documentation on HOCs