English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

ReactJS 이벤트

이 장에서는 이벤트를 사용하는 방법을 배웁니다.

간단한 예제

이는 단순한 예제로, 우리는 단일 컴포넌트만 사용합니다. 우리는 단순히 추가했습니다.onClick이벤트updateState버튼을 클릭하면 이 이벤트가 기능을 트리거합니다。

App.jsx

import React from 'react';
class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 'Initial data...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState() {
      this.setState({data: 'Data updated...'})
   }
   render() {
      return (
         <div>
            <button onClick={this.updateState}>CLICK</button>
            <h4{this.state.data}</h4>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/, document.getElementById('app'));

이렇게 될 것입니다.

아동 활동

필요할 때state부모 컴포넌트에서 자식 컴포넌트로부터 상태를 업데이트할 때, 부모 컴포넌트에서 이벤트 핸들러를 생성할 수 있습니다。updateState),그리고 이를 prop로 사용합니다。updateStateProp)부모 컴포넌트에 전달된 값을 자식 컴포넌트에서 호출할 수 있습니다。

App.jsx

import React from 'react';
class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 'Initial data...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState() {
      this.setState({data: 'Data updated from the child component...'})
   }
   render() {
      return (
         <div>
            <Content myDataProp = {this.state.data} 
               updateStateProp = {this.updateState}</Content>
         </div>
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         <div>
            <button onClick = {this.props.updateStateProp}>CLICK</button>
            <h3>{this.props.myDataProp}</h3>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/, document.getElementById('app'));

이렇게 될 것입니다.