React中的Context怎么用
What is Context今天在学习styled-components的 什么是Context当我们使用 而有的时候,我们不想让一个 怎样使用Context假设有个如下的结构: class Button extends React.Component { render() { return ( <button style={{background: this.props.color}}> {this.props.children} </button> ); } } class Message extends React.Component { render() { return ( <div> {this.props.text} <Button color={this.props.color}>Delete</Button> </div> ); } } class MessageList extends React.Component { render() { const color = "purple"; const children = this.props.messages.map((message) => <Message text={message.text} color={color} /> ); return <div>{children}</div>; } } 上面的例子中,我们把 const PropTypes = require('prop-types'); class Button extends React.Component { render() { return ( <button style={{background: this.context.color}}> {this.props.children} </button> ); } } Button.contextTypes = { color: PropTypes.string }; class Message extends React.Component { render() { return ( <div> {this.props.text} <Button>Delete</Button> </div> ); } } class MessageList extends React.Component { getChildContext() { return {color: "purple"}; } render() { const children = this.props.messages.map((message) => <Message text={message.text} /> ); return <div>{children}</div>; } } MessageList.childContextTypes = { color: PropTypes.string }; 通过给 如果未定义 可获取Context对象的勾子函数一旦组件定义了
无状态组件获取Context方法无状态组件同样可以通过给函数定义 const PropTypes = require('prop-types'); const Button = ({children},context) => <button style={{background: context.color}}> {children} </button>; Button.contextTypes = {color: PropTypes.string}; Context的更新不要更新Context!
如果想用的话,可以看下面的这个例子。 const PropTypes = require('prop-types'); class MediaQuery extends React.Component { constructor(props) { super(props); this.state = {type:'desktop'}; } getChildContext() { return {type: this.state.type}; } componentDidMount() { const checkMediaQuery = () => { const type = window.matchMedia("(min-width: 1025px)").matches ? 'desktop' : 'mobile'; if (type !== this.state.type) { this.setState({type}); } }; window.addEventListener('resize',checkMediaQuery); checkMediaQuery(); } render() { return this.props.children; } } MediaQuery.childContextTypes = { type: PropTypes.string }; 这里有个问题是,如果宿主组件的 不建议使用Context绝大多数的应用程序是不需要使用 如果你想要你的应用稳定,就不要使用它,这是一个实验性的API,在未来的版本更新中很有可能会被弃掉。 context最好的使用场景是隐式的传入登录的用户,当前的语言,或者主题信息。要不然所有这些可能就是全局变量,但是context让你限定他们到一个单独的React树里。 如果项目对数据管理较为复杂,推荐使用类似于redux或mobX这样的状态管理库,而不要使用 记录的过程是一种成长,欢迎大家关注我的github。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |