Part2- React 클래스 기반 구성 요소의 컨텍스트 API

=> 여기에 폴더 구조 이미지가 있습니다.



Index.js 코드:-_

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
)


App.js 코드:-

import React, { Component } from 'react'
import User from './User'
import { Provider1 } from './Context'

export default class App extends Component {
    state = {
        name: 'Rahul',
        value: 10
    }

    handleClickContext = () => {
        this.setState({
            value: this.state.value + 1
        })
    }

    render() {
        const contextValue = {
            data: this.state,
            handleClick: this.handleClickContext
        }

        return (
            // <myContext.Provider value={this.state.name}>
            <Provider1 value={contextValue}>
                <User />
            </Provider1>
        )
    }
}




User.js 코드:

import React, { Component } from 'react'
import Guest from './Guest'

export default class User extends Component {
  render() {
    return (
      <div>
        <h3>User component</h3>
        <Guest />
      </div>
    )
  }
}



Guest.js 코드:

import React, { Component } from 'react'
import { Consumer1 } from './Context'

export default class Guest extends Component {
    render() {
        return (
            <div>
                <h3>Guest Component</h3>
                <Consumer1> 
                    {({ data, handleClick }) =>
                        <>

                            <h4>{data.name}</h4>
                            <h4>{data.value}</h4>

                            <button onClick={handleClick}>Change Value</button>
                        </>
                    }
                </Consumer1>
            </div>
        )
    }
}




Context.js 코드:

import React from 'react'
const myContext1 = React.createContext();
export const Provider1 = myContext1.Provider;
export const Consumer1 = myContext1.Consumer; 


감사합니다.
다음에서 팔로우할 수 있습니다.

좋은 웹페이지 즐겨찾기