IT/React

React 💬10

금마s 2021. 2. 2. 15:08

🎈 Events 🎈

 

 

[ 기본 예제 ] 

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'));

 

 

💻

 

 

 

[ Child event ]

🔧 부모 컴포넌트의 state를 child에서 update해야한다.

 

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'));

 

 

💻

 

 

 

 

 

 

 

728x90

'IT > React' 카테고리의 다른 글

React 💬12  (0) 2021.02.02
React 💬11  (0) 2021.02.02
React 💬9  (0) 2021.02.02
React 💬8  (0) 2021.02.02
React 💬7  (0) 2021.02.02