contextType
指定context類型為創建的上下文,此時不需要用Consumer組件包裹,使用this.context即可訪問 會向上找最近的上下文并取值 最適合的場景:雜亂無章的組件都需要同一些數據;若單純為了不層層傳遞屬性,使用context是不合適的 Context弱點:弱化及污染組件的純度,導致組件復用性降低 使用組合組件(組件嵌套),則不需要使用context
使用context
const CityContext = React. createContext ( { value: 'hongkong' , label: '香港' } )
class Content extends React . Component { render ( ) { return ( < h1> { this . props. label} < / h1> ) }
}
class Selector extends React . Component { static contextType = CityContextrender ( ) { return ( < > < selectvalue= { this . context. name} onChange= { ( e) => { this . props. changeCity ( { value: e. target. value, label: e. target[ e. target. selectedIndex] . label} ) } } > < option value= "hongkong" > 香港< / option> < option value= "hangzhou" > 杭州< / option> < option value= "fujian" > 福建< / option> < option value= "manila" > 馬尼拉< / option> < / select> < / > ) }
}
class Main extends React . Component { state = { cityInfo: { value: 'hongkong' , label: '香港' } } changeCity = ( obj) => { this . setState ( { cityInfo: obj} ) } render ( ) { return ( < > < CityContext. Provider value= { this . state. cityInfo} > < Content label= { this . state. cityInfo. label} / > < Selector changeCity= { this . changeCity} / > < / CityContext. Provider> < / > ) }
}
ReactDOM. render ( < Main / > , document. getElementById ( 'app' ) )
使用組合組件
class Content extends React . Component { render ( ) { return ( < div> < h1> { this . props. label} < / h1> < div> { this . props. selector} < / div> < / div> ) }
}
class Selector extends React . Component { render ( ) { return ( < > < selectvalue= { this . props. dataForSelector. name} onChange= { ( e) => { this . props. changeCity ( { value: e. target. value, label: e. target[ e. target. selectedIndex] . label} ) } } > < option value= "hongkong" > 香港< / option> < option value= "hangzhou" > 杭州< / option> < option value= "fujian" > 福建< / option> < option value= "manila" > 馬尼拉< / option> < / select> < / > ) }
}
class Main extends React . Component { state = { cityInfo: { value: 'hongkong' , label: '香港' } } changeCity = ( obj) => { this . setState ( { cityInfo: obj} ) } render ( ) { return ( < > < Content label= { this . state. cityInfo. label} selector= { < Selector changeCity= { this . changeCity} dataForSelector= { this . state. cityInfo} / > } / > { } < / > ) }
}
ReactDOM. render ( < Main / > , document. getElementById ( 'app' ) )