【问题标题】:innerRef to third party component对第三方组件的内部引用
【发布时间】:2018-01-23 07:39:39
【问题描述】:

我将 Redux Form 与 Styled Components 一起使用。

我想获得一个 Redux 表单字段的 ref,这样我就可以在某些条件下聚焦它。

代码看起来像:(有点简化)

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也是一个样式化的组件,但没必要为了问题展示出来)

提前致谢。

【问题讨论】:

    标签: reactjs react-redux redux-form styled-components


    【解决方案1】:

    哇!我写了redux-form,我很喜欢styled-components,但我从来没有想过要写styled(Field)。这很疯狂,因为我不认为 Field 是一个可以“样式化”的“渲染组件”。

    但是,我认为您缺少的拼图是您需要将a withRef prop 传递给Field,这将使您能够使用getRenderedComponent() 来获取实际的textarea 组件。比如:

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

    我只是在这里推测。我自己从未尝试过这种模式。

    【讨论】:

      猜你喜欢
      • 2017-12-30
      • 1970-01-01
      • 2018-11-23
      • 2017-05-10
      • 2010-09-14
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多