javascript - 如何在reactjs中使用this.refs从输入类型获取值?

标签 javascript reactjs

无法使用 this.refs 获取输入类型的值... 如何从输入类型获取该值

   export class BusinessDetailsForm extends Component {
      submitForm(data) {
        console.log(this.refs.googleInput.value)
        }
      }
      reder() {
        return(
          <form onSubmit={this.submitForm}>
            <Field type="text"
              name="location"
              component={GoogleAutoComplete}
              id="addressSearchBoxField"
              ref="googleInput"
            />
          </form>
        )
      }
    }

最佳答案

您应该避免 ref="googleInput",因为它现在被视为旧版。你应该声明

ref={(googleInput) => { this.googleInput = googleInput }}

在处理程序内部,您可以使用 this.googleInput 来引用该元素。

然后在您的 submitForm 函数中,您可以使用以下命令获取文本值 this.googleInput._getText()

字符串引用是遗留的 https://facebook.github.io/react/docs/refs-and-the-dom.html

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

编辑

React 16.3开始,创建引用的格式为:

class Component extends React.Component 
{
        constructor() 
        {
            this.googleInput = React.createRef();
        }

        render() 
        {
            return 
            (
                <div ref={this.googleInput}>
                    {/* Details */}
                </div>
            );
        }
    }

关于javascript - 如何在reactjs中使用this.refs从输入类型获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43137275/

相关文章:

reactjs - 使用Webpack使所有图像文件指向CDN

javascript - React/Redux 在组件级别链接异步 thunk 操作

javascript - React Router 的 HashRouter 重定向到 <base> 标签 url

JavaScript 函数发送字符串但接收 bool 值

javascript - 变量和数字的正则表达式匹配

javascript - 如何在对象解构赋值的左侧使用它?

reactjs - React/Typescript - 使用 ref 时出现 typescript 错误 - 类型 'current' 上不存在属性 '(instance: HTMLInputElement | null) => void'

javascript - Aptana "Missing semicolon"警告

javascript - fullcalendar.js - 删除按钮点击事件

reactjs - react 路由器 : 'history' is missing in type