首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在reactjs中使用this.refs从输入类型获取值?

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

Stack Overflow用户
提问于 2017-03-31 17:32:22
回答 6查看 105.4K关注 0票数 35

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

代码语言:javascript
复制
   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>
        )
      }
    }
EN

回答 6

Stack Overflow用户

发布于 2017-03-31 18:55:42

代码语言:javascript
复制
getValue: function() {
    return this.refs.googleInput.value;
  }
票数 8
EN

Stack Overflow用户

发布于 2017-04-01 00:27:27

我认为更常用的方法是使用state而不是refs,尽管在本例中需要更多的代码,因为您只有一个输入。

代码语言:javascript
复制
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

票数 6
EN

Stack Overflow用户

发布于 2020-11-09 21:13:33

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

代码语言:javascript
复制
// 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>
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43137275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档