2017-08-15 125 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()} 
/> 

我只是揣测这里。我从来没有尝试过这种模式。