programing

reactjs의 this.refs를 사용하여 입력 유형에서 값을 얻는 방법

linuxpc 2023. 4. 1. 08:32
반응형

reactjs의 this.refs를 사용하여 입력 유형에서 값을 얻는 방법

이.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를 사용한 적이 있다면, ref 속성이 "textInput"과 같은 문자열이고 DOM 노드가 this.refs.textInput으로 액세스되는 오래된 API에 익숙할 것입니다.string ref는 몇 가지 문제가 있어 레거시라고 간주되며 향후 출시에서 삭제될 가능성이 높기 때문에 이 문제를 피하는 것이 좋습니다.현재 참조에 액세스하기 위해 이.refs.textInput을 사용하고 있다면 대신 콜백 패턴을 사용하는 것이 좋습니다.

편집

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단, 이 경우 입력은 1개뿐이므로 조금 더 많은 코드입니다.

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 를 참조해 주세요.

사용.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- 현재 상태가 아닌 마지막 상태가 반환되므로 사용 시 주의하시기 바랍니다.

2018년에는 다음과 같이 컨스트럭터에 작성해야 합니다.클래스의 컨스트럭터에서는 다음과 같은 것을 추가해야 합니다.this.input = React.createRef()

예: https://reactjs.org/docs/uncontrolled-components.html

위의 답변(https://stackoverflow.com/a/52269988/1978448))을 시험해보니, ref를 그 상태로 둘 때만 효과가 있었고, 컴포넌트의 속성을 만들었을 때는 효과가 없었습니다.

컨스트럭터:

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

handleSubmit에 payload 객체를 생성하여 다음과 같이 서버에 게시합니다.

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

react documents는 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;

도움이 되길 바랍니다.

언급URL : https://stackoverflow.com/questions/43137275/how-to-get-values-from-input-types-using-this-refs-in-reactjs

반응형