React 之 Provider

428 阅读1分钟

参考页面

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Context 提供了一种在组件树中传递数据但又不使用props 的方法;

In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

在一个常规的React项目中, 数据躺下传递(父=> 子)是通常props的; 但传递一些指定的props时会很麻烦(例如引用、皮肤等)需要很多组件都使用的数据; Context 提供了一种在组件间共享数据但又不需要在每一级中明确地传递props的方法;

创建context
let MyContext = createContext(Theme.light);
class RenderItem extends Component{
	render(){
		return (

		<>
				<RenderItemSon value="1" />
				theme === {this.context.bgc}
			</>
		)
	}
}
RenderItem.contextType = MyContext;

在最外层添加context
class User extends Component{
	constructor(props){
		super(props);
		this.state = {
			list: [1,2,3,4],
			theme: Theme.light,
		}
	}
	componentDidMount(){
		console.log(this.props);
	}
	render(){
		console.log(MyContext);
		return (
			<MyContext.Provider value={this.state.theme}>
				<div onClick={()=>this.setState({theme: Theme.dark})}>dark</div>
				<div onClick={()=>this.setState({theme: Theme.light})}>light</div>
				{this.state.list.map(item=><RenderItem key={item} value={item} />)}
			</MyContext.Provider>
		)
	}
}

function component 使用context
const RenderItemSon = function(props){
	let theme = useContext(MyContext);
	return <div>{props.value}--theme=={theme.bgc}</div>
}

class Component 使用context
class RenderItem extends Component{
	render(){
		return (

		<>
				<RenderItemSon value="1" />
				theme === {this.context.bgc}
			</>
		)
	}
}