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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43137275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:42:08  来源:igfitidea点击:

How to get values from input types using this.refs in reactjs?

javascriptreactjs

提问by Ashh

Not able to get values of input type using this.refs... how to get that values from input type

无法使用 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>
        )
      }
    }

采纳答案by Dan

You should avoid ref="googleInput"as it is now considered legacy. You should instead declare

你应该避免,ref="googleInput"因为它现在被认为是遗产。你应该改为声明

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

Inside of your handler, you can use this.googleInputto reference the element.

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

Then inside of your submitFormfunction, you can obtain the text value with this.googleInput._getText()

然后在您的submitForm函数内部,您可以使用 this.googleInput._getText()

String refs are legacyhttps://facebook.github.io/react/docs/refs-and-the-dom.html

字符串引用是遗留的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,您可能熟悉一个旧的 API,其中 ref 属性是一个字符串,如“textInput”,并且 DOM 节点作为 this.refs.textInput 访问。我们建议不要这样做,因为字符串引用有一些问题,被认为是遗留的,并且可能会在未来的版本之一中被删除。如果您当前正在使用 this.refs.textInput 来访问 refs,我们建议您改用回调模式。

Edit

编辑

From React 16.3, the format for creating refsare:

React 16.3 开始,创建refs的格式是:

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

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

回答by mohitSehgal

using ref={ inputRef => this.input = inputRef }is considered legacy now. In React 16.3onwards, you can use the code below,

使用ref={ inputRef => this.input = inputRef }现在被认为是遗产。在 React 16.3之后,你可以使用下面的代码,

class MyForm extends React.Component {
    constructor(props) {
        //...
        this.input = React.createRef();
    }

    handleSubmit(event) {
        alert('A name was submitted: ' + this.input.current.value);
        event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <label>
                    Name:
                    <input type="text" ref={this.input} />
                </label>
                <input type="submit" value="Submit" />
            </form>
        );
    }
}

EDIT: thanks for the comment @stormwild

编辑:感谢@stormwild的评论

回答by Johib Khan

getValue: function() {
    return this.refs.googleInput.value;
  }

回答by adrice727

I think the more idiomatic way is to use stateinstead of refs, although it's a little more code in this case since you only have a single input.

我认为更惯用的方法是使用state而不是refs,尽管在这种情况下它的代码更多一些,因为您只有一个输入。

export class BusinessDetailsForm extends Component {

  constructor(props) {
    super(props);
    this.state = { googleInput: '' };
    this.defaultValue = 'someValue';
    this.handleChange = this.handleChange.bind(this);
    this.submitForm = this.submitForm.bind(this);
  }

  handleChange(e) {
    const { field, value } = e.target;
    this.setState({ [field]: value });
  }
  submitForm() {
    console.log(this.state.googleInput);
  }
  render() {
    return (
      <Formsy.Form onSubmit={this.submitForm} id="form_validation">
        <Field type="text"
          name="googleInput"
          onChange={this.handleChange}
          component={GoogleAutoComplete}
          floatingLabelText="location"
          hintText="location"
          id="addressSearchBoxField"
          defaultValue={this.defaultValue}
          onSelectPlace={this.handlePlaceChanged}
          validate={[ required ]}
        />
      </Formsy.Form>
    );
  }
}

See https://facebook.github.io/react/docs/forms.html#controlled-components.

请参阅https://facebook.github.io/react/docs/forms.html#controlled-components

回答by Navneet kumar

Using RN 0.57.8when tried this.googleInput._getText(), It resulted in error _getText is not a functionso i printed this.googleInputin console and found that _getText()is a function inside _root

RN 0.57.8尝试使用时this.googleInput._getText(),它导致错误,_getText is not a function所以我this.googleInput在控制台中打印并发现这_getText()是一个函数_root

  1. this.googleInput._root._getText()
  2. this.googleInput._root._lastNativeText- This will return the last state not the current state please be careful while using it.
  1. this.googleInput._root._getText()
  2. this.googleInput._root._lastNativeText- 这将返回最后一个状态而不是当前状态,请在使用时小心。

回答by NULL pointer

I tried the answer above (https://stackoverflow.com/a/52269988/1978448) and found it only worked for me when I put the refs in the state, but not when I just made them properties of the component.

我尝试了上面的答案(https://stackoverflow.com/a/52269988/1978448),发现它只在我将 refs 置于 state 中时才对我有用,但当我刚刚将它们设为组件的属性时就不行了。

Constructor:

构造函数:

this.state.refs={
  fieldName1: React.createRef(),
  fieldName2: React.createRef()
};

and in my handleSubmit I create a payload object to post to my server like this:

在我的 handleSubmit 中,我创建了一个有效负载对象来发布到我的服务器,如下所示:

var payload = {
  fieldName1: this.state.refs.fieldName1.current.value,
  fieldName2: this.state.refs.fieldName2.current.value,
}

回答by bjoern

The react docu explains it very well: https://reactjs.org/docs/refs-and-the-dom.html

反应文档很好地解释了它:https: //reactjs.org/docs/refs-and-the-dom.html

this is considered legacy:

这被认为是遗产:

yourHandleMethod() {
  this.googleInput.click();
};

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

whereas, this is considered the way to go:

而,这被认为是要走的路:

constructor(props){
  this.googleInput = React.createRef();
};
yourHandleMethod() {
  this.googleInput.current.click();
};
yourRenderCode(){
  <yourHTMLElement
    ref={this.googleInput}
  />
};

回答by yestema

In 2018 you should write in constructor this: In constructor of class you should add something like this.input = React.createRef()

在 2018 年,您应该在构造函数中这样写:在类的构造函数中,您应该添加类似 this.input = React.createRef()

Examples here: https://reactjs.org/docs/uncontrolled-components.html

这里的例子:https: //reactjs.org/docs/uncontrolled-components.html

回答by Alex

From React 16.2, you can use: React.createRef

从 React 16.2 开始,你可以使用:React.createRef

See more: https://reactjs.org/docs/refs-and-the-dom.html

查看更多:https: //reactjs.org/docs/refs-and-the-dom.html

1. using ref={ inputRef => this.input = inputRef }

1. 使用 ref={ inputRef => this.input = inputRef }

Exam:

考试:

import React, { Component } from 'react';

class Search extends Component {
    constructor(props) {
        super(props);

        this.name = React.createRef();

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.props.onSearch(`name=${this.name.value}`);
    }

    render() {
        return (
            <div>
                <input
                    className="form-control name"
                    ref={ n => this.name = n }
                    type="text"
                />

                <button className="btn btn-warning" onClick={ this.handleClick }>Search</button>
            </div>
        );
    }
}

export default Search;

ref={ n => this.name = n } Use Callback Refs -> see

ref={ n => this.name = n } 使用回调引用 ->

Or:

或者:

2. this.name.current.focusTextInput()

2. this.name.current.focusTextInput()

    class Search extends Component {
        constructor(props) {
            super(props);

            this.name = React.createRef();

            this.handleClick = this.handleClick.bind(this);
        }

        handleClick() {
            this.props.onSearch(`name=${this.name.current.value}`);
        }

        render() {
            return (
                <div>
                    <input
                        className="form-control name"
                        ref={this.name}
                        type="text"
                    />

                    <button className="btn btn-warning" onClick={ this.handleClick }>Search</button>
                </div>
            );
        }
    }

    export default Search;

Hope it will help you.

希望它会帮助你。