网站建设图片上传,档案信息网站建设工作经验,北京网站seo优化排名,网站项目整体思路contextType
指定context类型为创建的上下文#xff0c;此时不需要用Consumer组件包裹#xff0c;使用this.context即可访问会向上找最近的上下文并取值最适合的场景#xff1a;杂乱无章的组件都需要同一些数据#xff1b;若单纯为了不层层传递属性#xff0c;使用contex…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 valuehongkong香港/optionoption valuehangzhou杭州/optionoption valuefujian福建/optionoption valuemanila马尼拉/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 (divh1{this.props.label}/h1div{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 valuehongkong香港/optionoption valuehangzhou杭州/optionoption valuefujian福建/optionoption valuemanila马尼拉/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))