2019-03-10
回答
Context 提供了一种传递数据的方式,他不需要你手动的通过组件树从上至下逐层传递属性。例如:在应用程序中需要通过许对组件才能获取用户身份验证、本地设置、UI 主题。
import React from 'react'; import ReactDOM from 'react-dom'; const ThemeContext = React.createContext({ background: 'red', color: 'white' }); class App extends React.Component { render () { return ( <ThemeContext.Provider value={{background: 'green', color: 'white'}}> <Header /> </ThemeContext.Provider> ); } } class Header extends React.Component { render () { return ( <Title>Hello React Context API</Title> ); } } class Title extends React.Component { render () { return ( <ThemeContext.Consumer> {context => ( <h1 style={{background: context.background, color: context.color}}> {this.props.children} </h1> )} </ThemeContext.Consumer> ); } }
加分回答
- Context 提供了一种通过 React 组件树传递数据的方法,他不需要手动传递属性。
- Context 主要为解决 React 组件树中被认为全局数据的共享。
- 除了实例中的
context
,React 组件还可以通过constructor(props, context)
、componentWillReceiveProps(nextProps, nextContext)
、shouldComponentUpdate(nextProps, nextState, nextContext)
和componetWillUpdate(nextProps, nextState, nextContext)
直接访问父组件提供的 Context。 - 使用 Context,可以跨越组件进行数据的传递:
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于