如何在ReactJS中使用this.refs获取输入类型的值?

45

使用this.refs无法获取input类型的值...如何从输入类型中获取那些值

   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>
        )
      }
    }
10个回答

28

由于现在已被视为遗留代码,因此您应避免使用ref="googleInput"。您应该改为声明

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

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

然后在你的submitForm函数内,你可以使用this.googleInput._getText()来获取文本值。

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

如果你之前有使用过React,你可能熟悉旧API,其中ref属性是一个字符串,像"textInput"一样,DOM节点通过this.refs.textInput访问。我们建议不要使用这种方法,因为字符串引用有一些问题,被认为是遗留问题,并有可能在将来的版本中删除。如果您当前正在使用 this.refs.textInput 访问引用,请改用回调模式。

编辑

React 16.3开始,创建Refs的格式如下:

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

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

1
@ShubhamKhatri 如果你认为这个答案与问题无关,请考虑给它一个踩。问题的提问者询问了如何使用 ref 来获取输入框的值,而这个答案提供了解决方案以满足这个需求。 - Dan
17
无法运行,出现错误信息“Uncaught TypeError: _this.googleInput._getText is not a function”。 - Thidasa Pankaja
3
还在使用_getText()的,请扣1分。应该使用this.googleInput.current.value - Phil

18

ref={inputRef => this.input = inputRef}现在被认为是过时的了。在React16.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>
        );
    }
}

编辑:感谢@stormwild的评论。


React.createRef是在React 16.3中引入的。如果您使用的是早期版本的React,则建议使用回调refs。https://reactjs.org/docs/refs-and-the-dom.html - stormwild
我们如何使用 refs 来设置输入标签的值? - Siluveru Kiran Kumar

14

如果有人想知道如何使用Hooks实现ref:

// Import
import React, { useRef } from 'react';


const Component = () => {
    // Create Refs
    const exampleInput = useRef();

    const handleSubmit = (e) => {
        e.preventDefault();
   
         const inputTest = exampleInput.current.value;

     }

    return(
        <form onSubmit={handleSubmit}>
            <label>
                Name:
                <input type="text" ref={exampleInput} />
            </label>
            <input type="submit" value="Submit" />
        </form>
}

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

6

我认为更符合惯用法的方式是使用 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>
    );
  }
}

请查看https://facebook.github.io/react/docs/forms.html#controlled-components,该页面涉及到控制组件的相关内容。

我一直很喜欢你在这里使用的handleChange方法。我知道这是一个旧帖子,但是以防有人看到这个答案,这里是一个更加“甜美”的语法:handleChange = ({ target: { name, value } }) => this.setState({ [ name ]: value }); - Joshua Underwood
1
将文本输入框的值保持在“state”中会给子组件带来大量重新渲染的问题;使用“ref”可以避免这种情况,并且是良好的实践。 - Daydream Nation
1
@DaydreamNation 我不确定头痛是什么。根据React文档,“实现这一点的标准方法是使用一种称为“受控组件”的技术。” - adrice727

2
当我使用RN 0.57.8时,尝试使用this.googleInput._getText(),结果出现错误_getText不是一个函数,所以我在控制台中打印了this.googleInput,并发现_getText()是_root内的一个函数。
以下是可行的解决方法: 1. 使用this.googleInput._root._getText() 2. 使用this.googleInput._root._lastNativeText - 这将返回上一个状态而非当前状态,请在使用时小心。

虽然_root._getText()方法并没有给我我要找的确切内容,但是你在Chrome的React扩展程序中寻找相关方法的思路帮助我找到了需要的方法。 - Uday

1
我尝试了上面的答案(https://dev59.com/nVgQ5IYBdhLWcg3wMhLn#52269988),发现只有在将引用放入状态中时才能正常工作,而不是仅将其作为组件属性进行设置。
构造函数:
this.state.refs={
  fieldName1: React.createRef(),
  fieldName2: React.createRef()
};

在我的handleSubmit函数中,我创建了一个负载对象以向服务器发送POST请求,如下所示:
var payload = {
  fieldName1: this.state.refs.fieldName1.current.value,
  fieldName2: this.state.refs.fieldName2.current.value,
}

1

1

React文档对此进行了很好的解释:https://reactjs.org/docs/refs-and-the-dom.html

这被认为是遗留问题:

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

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

而这被认为是正确的做法:
constructor(props){
  this.googleInput = React.createRef();
};
yourHandleMethod() {
  this.googleInput.current.click();
};
yourRenderCode(){
  <yourHTMLElement
    ref={this.googleInput}
  />
};

1
从React 16.2开始,你可以使用:React.createRef 查看更多:https://reactjs.org/docs/refs-and-the-dom.html 1. 使用ref={ inputRef => this.input = inputRef } 示例:
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 } 使用回调 Refs -> 查看

或者:

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;

希望它能对你有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接