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



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

如果你以前使用过 React,你可能熟悉一个较旧的 API,其中 ref 属性是一个字符串,比如 "textInput",并且 DOM 节点以 this.refs.textInput 的形式访问。我们建议不要这样做,因为字符串引用存在一些问题,被视为遗留版本,并且可能会在未来的一个版本中删除。如果您当前使用 this.refs.textInput 来访问 refs,我们建议改用回调模式。

编辑

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

class Component extends React.Component 
{
        constructor() 
        {
            this.googleInput = React.createRef();
        }
        render() 
        {
            return 
            (
                <div ref={this.googleInput}>
                    {/* Details */}
                </div>
            );
        }
    }

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

编辑:感谢您的评论@stormwild

如果有人想知道如何使用钩子实现 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>
}
getValue: function() {
    return this.refs.googleInput.value;
  }

我认为更惯用的方法是使用 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。

尝试

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

  1. this.googleInput._root._getText()
  2. this.googleInput._root._lastNativeText - 这将返回最后状态而不是当前状态,请在使用它时小心。

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

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

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

构造 函数:

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

在我的句柄提交中,我创建一个有效负载对象以发布到我的服务器,如下所示:

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

react docu 解释得很好: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}
  />
};

从 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 } 使用回调引用 -> 参见

或:

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;

希望对您有所帮助。

最新更新