Props in Class Component

ကျတော်က ဒီစာအုပ်မှာ class component တွေနဲ့ပါ တွဲပီးတော့ ရေးသွားဖို့ တွေးထားတာဆိုတော့ props

တွေကိုလည်း class component တွေထဲမှာ ဘယ်လိုမျိုး အသုံးပြုရမှာလည်းဆိုတာကို ပါ

တခါတည်းလေ့လာသွားကြရအောင် အရင်ဆုံး ကျတော်တို့ class component တစ်ခုကို ဖန်တီးကြရအောင်

အရင်ဆုံး ကျတော်တို့ code တွေကို ဒီလိုလေးရေးလိုက်ပါမယ်

import {Component} from 'react'
class ClassComponent extends Component {
   constructor() {
      super()
   }
render(){
   return(
	<h1> Class Component </h1>
      )
   }
}
export default ClassComponent

အဲလိုမျိုးရေးပြီးတော့ ကျတော်တို့ ကုဒ်တွေကိုတချက် လေ့လာကြည့်လိုက်ရအောင်

ဒီထဲမှာ ကျတော်တို့က constructor ကို ထည့်ရေးထားတာကို မြင်ရပါလိမ့်မယ်

ကျတော်တို့ class component မှာက ကျတော့ functional လိုမျိုး props ကိုလက်ခံဖို့အတွက်

Parenthesis မပါဘူး အဲအတွက် ကျတော်တို့က constructor ကနေပြီးတော့ props ကိုလက်ခံပေးရမှာပါ

အဲလို လက်ခံလိုက်တော့မှ ကျတော်တို့ render လုပ်တဲ့အခါ props ရဲ့ data တွေကို အသုံးပြုလို့ရသွားတာပါ

အဲလိုမျိုးရေးပြီးတော့ ကျတော်တို့က passing လုပ်လာတဲ့ data ကို ပြန်အသုံးပြုချင်တဲ့အခါကျတော့

render method ထဲမှာ သွားပြီးတော့အသုံးပြုပေးရပါတယ်

render(){
    console.log(this.props)
    return(
        <h1> Class Component </h1>
    )
}

အဲမှာ ကြည့်လိုက်တဲ့အခါမှာ ကျတော်တို့ သတိထားမိမှာက this keyword ကြီးပါနေတာကိုပါမြင်ရပါလိမ့်မယ်

ဘာလို့လည်းဆိုတော့ အဲဒီ props က class Child ထဲမှာ ရှိနေတာမလို့ သူ့ကို ကျတော်တို့က ပြန်ညွှန်ပေးရပါတယ်

အဲလိုမျိုး ရေးပြီးတော့ ကျတော်တို့က browser မှာပေါ်စေချင်ရင် ဒီလိုရေးပေးရပါမယ်

import {Component} from 'react'
class Child extends Component {
        constructor(props){
        super(props)
    }
    render(){
        console.log(this.props)
        return(
            <h1>{this.props.name}</h1>
        )
    }
}
export default Child
result in browser

အဲလောက်ဆိုရင်တော့ ကျတော်တို့ class component ထဲမှာလည်း props တွေကို ဘယ်လိုမျိုး ယူသုံးလို့ရတာလည်း

ကို မြင်သာမယ်ထင်ပါတယ်

သူ့ကို လည်း object destructuring လုပ်ချင်ရင်လည်းလုပ်လို့ရပါတယ်

ဘယ်လိုမျိုးဖြစ်သွားမလဲဆိုတော့

render(){
    console.log(this.props)
    const { name } = this.props
    return(
        <h1>{name}</h1>
    )
}

အဲလိုလေးရေးပြီးတော့အသုံးပြုလို့ရသွားပါပီ

ဒီလောက်ဆိုရင်တော့ ကျတော်တို့ props တွေကို ဘယ်လိုမျိုးအလုပ်လုပ်တာလည်း ဆိုတာကိုမြင်သာသွားမယ်

လို့ထင်ပါတယ်

Last updated