"state"를 사용하여 입력한 문자의 수를 세어 보세요!

10296 단어 ReactJavaScript

개요


지난번 기사에서 프로포즈를 정리했으니 이번에는 프로포즈처럼 컨디션 관리를 하는state를 정리하고 싶어요!
저번 보도
React의 "props"를 이해하세요!
다음번
"Redux"를 사용하여 상태 관리를 수행하십시오!

소위 state


React의 Component는 Component 내부에서 상태를 유지할 수 있습니다.이 내부 상태를state라고 합니다.
프로포즈가 부모의 컴포니트에서 얻은 값인 것에 비해 state는 컴포니트 내부에서만 사용된다는 점은 프로포즈와 다르다.
또한props는 변경할 수 없는 값이고state는 변경할 수 있습니다.

코드를 실제로 써보세요!


그럼 실제 코드에서'state'를 어떻게 사용하고 입력한 문자수를 되돌려 주는 프로그램을 예로 들어보세요!
import React, {Component} from 'react';

const App = () => <Counter />;

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {count: 0, textValue: 'initial value'};
  }

  handleTextChange(textValue) {
    this.setState({textValue});
  }

  handleCountChange(textLength) {
    this.setState({count: textLength});
  }

  render() {
    return (
      <React.Fragment>
        <div>文字数: {this.state.count}</div>
        <textarea
          type="text"
          onChange={e => this.handleTextChange(e.target.value)}
          onKeyUp={e => this.handleCountChange(e.target.value.length)}
        />
      </React.Fragment>
    );
  }
}

export default App;
상기 코드를 쓰면 다음과 같은 기능을 실현할 수 있다

해설

constructor는 Component 생성 시 가장 먼저 실행되는 방법입니다.여기에 this.state = {count: 0, textValue: 'initial value'};라고 적으면 다른 방법this.state.count 등에서'state'를 얻을 수 있다.
constructor(props) {
    super(props);
    this.state = {count: 0, textValue: 'initial value'};
  }
setState는 상태를 바꾸려고 할 때 사용하는 규정 방법이다.setState를 사용하여 상태와 관련된 DOM을 다시 그립니다.
  handleTextChange(textValue) {
    // this.setState({textValue: textValue}); 下記のように省略可
    this.setState({textValue});
  }

  handleCountChange(textLength) {
    this.setState({count: textLength});
  }
<textarea>의 속성에 onChangeonKeyUptextarea의 내용이 바뀌었을 때와 키보드의 임의의 키를 놓았을 때 각각'state'를 변경하는 이벤트가 발생합니다!
그리고 <div>文字数: {this.state.count}</div>라고 쓰여 있으면 브라우저에 재현textarea할 수 있는 글자 수입니다.
render() {
    return (
      <React.Fragment>
        <div>文字数: {this.state.count}</div>
        <textarea
          type="text"
          onChange={e => this.handleTextChange(e.target.value)}
          onKeyUp={e => this.handleCountChange(e.target.value.length)}
        />
      </React.Fragment>
    );
  }

최후


다음부터는 "Redux"를 정리하고 싶어요!

참고 자료

  • 이제 리액션 시작해.js-POP와state,그리고refs~
  • React.js에서 Form 처리
  • React에서 양식 사용
  • 양식에서 입력한 값 - BppLOG 를 React 로 표시
  • State란? -React 시작
  • 좋은 웹페이지 즐겨찾기