development

ReactJS를 사용하여 입력 필드의 값을 얻는 방법은 무엇입니까?

big-blog 2020. 6. 16. 07:53
반응형

ReactJS를 사용하여 입력 필드의 값을 얻는 방법은 무엇입니까?


다음과 같은 React 구성 요소가 있습니다.

export default class MyComponent extends React.Component {

    onSubmit(e) {
        e.preventDefault();
        var title = this.title;
        console.log(title);
    }

    render(){
        return (
            ...
            <form className="form-horizontal">
                ...
                <input type="text" className="form-control" ref={(c) => this.title = c} name="title" />
                ...
            </form>
            ...
            <button type="button" onClick={this.onSubmit} className="btn">Save</button>
            ...
        );
    }

};

콘솔이 나에게주는 undefined-이 코드에 어떤 문제가 있습니까?


MyComponent extends React.Component 클래스에서 생성자를 사용해야합니다.

constructor(props){
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

그럼 당신은 제목의 결과를 얻을 것이다


작업하고있는 React 버전과 후크 사용 여부에 따라 여기에 세 가지 답변이 있습니다.

먼저 첫 번째 것들:

이됩니다 : 당신이 제대로 (protip이 일을 할 수 있도록이 작품을 어떻게 반응하는지 이해하는 것이 중요 슈퍼 . 방법을 수행하는 사실이 설명하는 방법으로 웹 사이트 반응에 튜토리얼 운동 반응을 통해 잘 작성의 가치가 실행하고, 커버 모든 기본 소지품). 여기서 "적절하게"는 브라우저에서 렌더링되는 응용 프로그램 인터페이스를 작성하고 있음을 의미합니다. 모든 인터페이스 작업은 "웹 페이지를 작성하는 데 익숙하지 않은"React에서 발생합니다 (React 앱이 "웹 페이지"가 ​​아니라 "앱"인 이유).

React 애플리케이션은 다음 두 가지를 기반으로 렌더링됩니다.

  1. 부모가 선언 한 구성 요소의 속성은 부모가 수명주기 내내 수정할 수있는 해당 구성 요소의 인스턴스를 만듭니다.
  2. 구성 요소 자체의 내부 상태로, 자체 수명주기 동안 자체적으로 수정할 수 있습니다.

당신은 명시 적으로 무엇을하고 하지 당신이 사용에 반응 말할 때 당신이 그 사용 후 HTML 요소를 생성하고 반작용 사용할 때하고 <input>, 예를 들어, 당신이 하지 의 HTML 입력 요소를 생성, 당신이 말하는되는 입력 오브젝트 반응 생성 반응 HTML 입력 요소 렌더링 되며 이벤트 처리는 HTML 요소의 입력 이벤트를 보지만 제어하지는 않습니다 .

React를 사용할 때 사용자 상호 작용으로 구성 요소의 상태를 변경하여 사용자에게 (종종 조작 가능한) 데이터를 제공하는 응용 프로그램 UI 요소를 생성 하면 응용 프로그램 인터페이스의 일부가 다시 렌더링되어 새 상태가 반영 될 수 있습니다. 이 모델에서 상태는 웹에서 브라우저의 DOM 인 "렌더링에 사용되는 UI 라이브러리"가 아니라 항상 최종 권한입니다. DOM은이 프로그래밍 모델에서 거의 후유증입니다. React가 사용하는 특정 UI 프레임 워크 일뿐입니다.

따라서 입력 요소의 경우 논리는 다음과 같습니다.

  1. 입력 요소를 입력하면
  2. 입력 요소에는 아무런 변화가 없지만 React가 이벤트를 가로 채서 즉시 종료했습니다 .
  3. React는 이벤트 처리를 위해 설정 한 기능으로 이벤트를 전달합니다.
  4. 이 기능 상태 업데이트를 예약 할 수 있습니다 .
  5. 이 경우 React는 해당 상태 업데이트 (비동기 적으로!)를 실행 render하고 업데이트 후 상태 업데이트 가 상태를 변경경우에만 호출을 트리거합니다 .
  6. 이 렌더링이 발생한 후에UI에 "문자를 입력했다"고 표시됩니다.

이 모든 것은 밀리 초 단위 로 이루어 지지만, "페이지에서 입력 요소 만 사용"과 같은 방식으로 입력 요소에 입력 한 것처럼 보이지만 절대 그렇지 않습니다. 일어난.

따라서 React의 요소에서 값을 얻는 방법에 대해서는 다음과 같이 말했습니다.

ES5로 15 이하 반응

작업을 올바르게 수행하기 위해 구성 요소는 입력 필드를 통해 표시되는 상태 값을 가지며 UI 요소가 변경 이벤트를 구성 요소로 다시 보내도록 구성 할 수 있습니다.

var Component = React.createClass({
  getInitialState: function() {
    return {
      inputValue: ''
    };
  },

  render: function() {
    return (
      //...
      <input value={this.state.inputValue} onChange={this.updateInputValue}/>
      //...
    );
  },

  updateInputValue: function(evt) {
    this.setState({
      inputValue: evt.target.value
    });
  }
});

따라서 React에 updateInputValue함수를 사용하여 사용자 상호 작용을 처리하고 setState, 상태 업데이트를 예약하는 데 사용 하며, render탭핑 한다는 사실은 상태를 업데이트 this.state.inputValue한 후 다시 렌더링하면 사용자가 입력 한 내용에 따라 업데이트 텍스트를 보게된다는 것을 의미합니다.

의견에 따른 부록

UI 입력은 상태 값을 나타냅니다 (사용자가 중간에 탭을 닫고 탭이 복원되면 어떻게되는지 고려하십시오. 입력 한 모든 값을 복원해야합니까? 그렇다면 그 상태입니다). 따라서 대형 양식에는 수십 또는 백 개의 입력 양식이 필요한 것처럼 느껴질 수 있지만 React는 UI를 유지 관리 가능한 방식으로 모델링하는 것입니다 .100 개의 독립적 인 입력 필드가없고 관련 입력 그룹이 있으므로 각각을 캡처합니다. 구성 요소에 그룹화 한 다음 그룹 모음으로 "마스터"양식을 작성하십시오.

MyForm:
  render:
    <PersonalData/>
    <AppPreferences/>
    <ThirdParty/>
     ...

또한 거대한 단일 폼 구성 요소보다 유지 관리가 훨씬 쉽습니다. 상태 유지 보수를 통해 그룹을 구성 요소로 분할하십시오. 여기서 각 구성 요소는 한 번에 몇 개의 입력 필드 만 추적합니다.

또한 모든 코드를 작성하는 것이 "번거 롭다"고 생각할 수도 있지만, 이는 잘못된 저장입니다. 미래를 포함하여 귀하가 아닌 개발자는 실제로 모든 입력을 명시 적으로 연결하면 크게 이익을 얻을 수 있습니다. 코드 경로를 훨씬 쉽게 추적 할 수 있습니다. 그러나 항상 최적화 할 수 있습니다. 예를 들어 상태 링커를 작성할 수 있습니다

MyComponent = React.createClass({
  getInitialState() {
    return {
      firstName: this.props.firstName || "",
      lastName: this.props.lastName || "" 
      ...: ...
      ...
    }
  },
  componentWillMount() {
    Object.keys(this.state).forEach(n => {
      let fn = n + 'Changed';
      this[fn] = evt => {
        let update = {};
        update[n] = evt.target.value;
        this.setState(update);
      });
    });
  },
  render: function() {
    return Object.keys(this.state).map(n => {
      <input
        key={n} 
        type="text"
        value={this.state[n]}
        onChange={this[n + 'Changed']}/>
    });
  }
});

물론 이것의 개선 된 버전이 있으므로 https://npmjs.com 을 방문하여 가장 좋아하는 React 상태 연결 솔루션을 검색 하십시오 . 오픈 소스는 주로 다른 사람들이 이미 한 일을 찾고 모든 것을 처음부터 쓰는 대신 사용하는 것입니다.

반응 16 (및 15.5 과도) 및 '현대'JS

React 16부터 (15.5로 소프트 스타트) createClass콜은 더 이상 지원되지 않으며 클래스 구문을 사용해야합니다. 이것은 명백한 클래스 구문뿐만 아니라 "무료"를 수행 할 수 있는 this컨텍스트 바인딩 과 같은 두 가지 사항을 변경 createClass하므로, 여전히 작동하도록하려면 핸들러 this에서 컨텍스트를 익명으로 유지하기 위해 "뚱뚱한 화살표"표기법을 사용하십시오. 여기에 코드에서 우리는 사용 :onWhateveronChange

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ''
    };
  }

  render() {
    return (
      //...
      <input value={this.state.inputValue} onChange={evt => this.updateInputValue(evt)}/>
      //...
    );
  },

  updateInputValue(evt) {
    this.setState({
      inputValue: evt.target.value
    });
  }
});

또한 사람들 bind이 생성자에서 다음과 같이 모든 이벤트 처리 함수에 사용하는 것을 보았을 것입니다 .

constructor(props) {
  super(props);
  this.handler = this.handler.bind(this);
  ...
}

render() {
  return (
    ...
    <element onclick={this.handler}/>
    ...
  );
}

하지마

Almost any time you're using bind, the proverbial "you're doing it wrong" applies. Your class already defines the prototype, and so as programming model already defines the instance context. Don't put bind of top of that an use normal event forwarding instead of duplicating all your function calls in the constructor. Now you've increased your bug surface, and made it much harder to trace errors because the problem might be in your constructor instead of where you call your code. In addition of placing a burden of maintenance on others you (have or choose) to work with.

Yes, I know the react docs say it's fine. It's not, don't do it.

React 16.8, using function components with hooks

As of React 16.8 the function component (i.e. literally just a function that takes some props as argument can be used as if it's an instance of a component class, without ever writing a class) can also be given state, through the use of hooks.

If you don't need full class code, and a single instance function will do, then you can now use the useState hook to get yourself a single state variable, and its update function, which works roughly the same as the above examples, except without the setState function call:

import { useState } from 'react';

function myFunctionalComponentFunction() {
  const [input, setInput] = useState(''); // '' is the initial state value
  return (
    <div>
    <label>Please specify:</label>
    <input value={input} onInput={e => setInput(e.target.value)}/>
    </div>
  );
}

Previously the unofficial distinction between classes and function components was "function components don't have state", so we can't hide behind that one anymore: the difference between function components and classes components can be found spread over several pages in the very well-written react documentation (no shortcut one liner explanation to conveniently misinterpret for you!) which you should read so that you know what you're doing and can thus know whether you picked the best (whatever that means for you) solution to program yourself out of a problem you're having.


Managed to get the input field value by doing something like this:

import React, { Component } from 'react';

class App extends Component {

constructor(props){
super(props);

this.state = {
  username : ''
}

this.updateInput = this.updateInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}


updateInput(event){
this.setState({username : event.target.value})
}


handleSubmit(){
console.log('Your input value is: ' + this.state.username)
//Send state to the server code
}



render(){
return (
    <div>
    <input type="text" onChange={this.updateInput}></input>
    <input type="submit" onClick={this.handleSubmit} ></input>
    </div>
  );
}
} 

//output
//Your input value is: x

In react 16, I use

<Input id="number" 
       type="time" 
       onChange={(evt) => { console.log(evt.target.value); }} />

I succeeded in doing this by binding the "this" to the function updateInputValue(evt) with

this.updateInputValue = this.updateInputValue.bind(this);

However input value={this.state.inputValue} ... turned out to be no good idea.

Here's the full code in babel ES6 :

class InputField extends React.Component{


  constructor(props){
   super(props);
   //this.state={inputfield: "no value"};   
   this.handleClick = this.handleClick.bind(this);
   this.updateInputValue = this.updateInputValue.bind(this);
  }

  handleClick(){
   console.log("trying to add picture url");
   console.log("value of input field : "+this.state.inputfield);

  }

  updateInputValue(evt){
    //console.log("input field updated with "+evt.target.value);
    this.state={inputfield: evt.target.value};   

  }

  render(){
    var r; 
    r=<div><input type="text" id="addpixinputfield" 
            onChange={this.updateInputValue} />
      <input type="button" value="add" id="addpix" onClick={this.handleClick}/>
      </div>;    
    return r;
   }
}

your error is because of you use class and when use class we need to bind the functions with This in order to work well. anyway there are a lot of tutorial why we should "this" and what is "this" do in javascript.

if you correct your submit button it should be work:

<button type="button" onClick={this.onSubmit.bind(this)} className="btn">Save</button>

and also if you want to show value of that input in console you should use var title = this.title.value;


You can get an input value without adding 'onChange' function.

Just add to the input element a 'ref attr:

And then use this.refs to get the input value when you need it.


// On the state
constructor() {
  this.state = {
   email: ''
 }
}

// Input view ( always check if property is available in state {this.state.email ? this.state.email : ''}

<Input 
  value={this.state.email ? this.state.email : ''} 
  onChange={event => this.setState({ email: event.target.value)}
  type="text" 
  name="emailAddress" 
  placeholder="johdoe@somewhere.com" />

참고URL : https://stackoverflow.com/questions/36683770/how-to-get-the-value-of-an-input-field-using-reactjs

반응형