2017-08-15 126 views
0

我使用Redux Form和Styled Components。innerRef第三方組件

我想獲得一個Redux表單字段的引用,所以我可以將它集中在某些條件下。

代碼看起來是這樣的:(一點點簡化)

export const SomeForm =() => (
    <form onSubmit={handleSubmit} > 
    <FormLabel htmlFor="comment">Comment:</FormLabel> 
    <CommentTextArea 
     name="comment" 
     component="textArea" 
     maxLength="250" 
     innerRef={commentBox => this.commentBox = commentBox} 
    /> 
    </form> 
); 

CommentTextArea像這樣的風格的組件:

const CommentTextArea = styled(Field)` 
    background-color: grey; 
    border-radius: 3px; 
    color: black; 
    height: 6.5rem; 
    margin-bottom: 1rem; 
`; 

的問題是,innerRefthis值未定義。有沒有辦法訪問textArea的參考號並在必要時集中它?

FormLabel也是一種風格的組成部分,但不是必需的,以顯示它的問題)提前

感謝。

回答

1

哇!我寫了redux-form和我崇拜styled-components,但我從來沒有想過要做styled(Field)。這是非常狂野的,因爲我不認爲Field是可以「風格化」的「渲染組件」。

不過,我認爲你缺少一塊拼圖是,你需要傳遞a withRef propField,那麼這將使您能夠使用getRenderedComponent()以獲得實際textarea組件。喜歡的東西:

<CommentTextArea 
    name="comment" 
    component="textArea" 
    maxLength="250" 
    withRef 
    innerRef={commentBox => this.commentBox = commentBox.getRenderedComponent()} 
/> 

我只是揣測這裏。我從來沒有嘗試過這種模式。