2017-10-06 107 views
2

我試圖讓redux-form與TypeScript和樣式組件一起工作。在下面的代碼示例中,爲什麼它不適用於樣式化的輸入組件?輸入呈現,但每次按鍵都會丟失焦點。它也需要兩次點擊來聚焦元素。看起來像redux-form試圖控制從樣式組件返回的包裝元素? redux-form和styled-components都使用HOC - 高階組件將道具傳遞給底層元素。如何使用TypeScript和樣式組件進行縮減形式的工作?

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

是的,我終於想通了。我做了一個錯誤,那就是要創造我的渲染方法中風格的組分包裝:

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

顯然,這是不安全的應用HOC - render()中的高階組件。所以移動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

+0

嘿,我想知道爲什麼FieldHack需要首先存在。我的項目中遇到同樣的問題,但無法繞過這一步。你有沒有找到更好的解決方案來爲打字稿中的redux-form創建自定義組件? –

+1

FieldHack只是一個幫手,因爲你無法在render/TSX中使用給定類型的泛型(TypeScript泛型與反應標記衝突?)我認爲使用普通JavaScript可以使redux-form工作得更好。或者,也許我只是沒有弄清楚如何在TypeScript中做到這一點:) – Thomas

+0

啊好的,謝謝澄清。 :)我在redux-form和TypeScript方面遇到了很多麻煩,定義有點複雜。不能幫助沒有很多完整的例子。 –

相關問題