如何在 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>
        )
      }
    }

原文由 Ashh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 286
2 个回答

你应该避免 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 开始,创建 refs 的格式为:

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

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

原文由 Dan 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 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 的评论

原文由 mohitSehgal 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题