简体   繁体   English

Redux-Form,如何将Ref与renderField一起使用?

[英]Redux-Form, how to use a Ref with a renderField?

I'm trying to add a ref attribute to one of my redux-form fields.. Here's the code: 我正在尝试向我的redux表单字段之一添加ref属性。这是代码:

let renderField = ({input, label, placeholder, type, meta: {submitFailed, touched, error, pristine}}) =>

  <div className={classNames("form-group", {
    "has-danger": (submitFailed && error) || (!pristine && touched && error),
    "has-success": !pristine && touched && !error
  })}>
    <textarea {...input} type={type} placeholder={placeholder} className={touched ? (error ? "form-control form-control-danger" : "form-control form-control-success") : "form-control"} />
  </div>

..... within the render func .....在渲染功能内

      <Field
        name="message"
        type="textarea"
        component={renderField}
        placeholder="Enter your message..."
        validate={[required]}
        ref="message"
        withRef={true}
      />

I'm getting the following error: 我收到以下错误:

Warning: Stateless function components cannot be given refs (See ref "renderedComponent" in renderField created by ConnectedField). Attempts to access this ref will fail

How can I get a ref added to my redux-form Field? 如何将引用添加到我的redux-form字段?

You should create class instead of function. 您应该创建类而不是函数。

import React, { Component } from 'react';

export default class RenderField extends Component {
  render() {...}
}

The error is telling you that you need to create a stateful component. 该错误告诉您需要创建一个有状态的组件。 You can do this by extending React.Component . 您可以通过扩展React.Component来做到这一点 See this from the docs on how to convert an existing functional component. 从如何将现有的功能组件的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM