React高级指南(九)【Context】
在React中,在React组件中很容易追踪数据流。当你观察组件时,你可以找出哪些属性(props)被传递,这使得你的应用非常容易理解。 在某些场景下,你想在整个组件树中传递数据,但却不想手动地在每一层传递属性。你可以直接在React中使用强大的 为什么不要使用Context绝大多数的应用程序不需要使用 如果你希望使用应用程序更加稳定就不要使用context。这只是一个实验性的API并且可能在未来的React版本中移除。 如果你不熟悉React或者Mobx这类state管理库,就不要使用 如果你不是一个有经验的React开发者,就不要使用 如果你不顾这些警告仍然坚持使用 如何使用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>;
}
}
在这个例子中,我们手动地传递 class Button extends React.Component {
render() {
return (
<button style={{'{{'}}background: this.context.color}}>
{this.props.children}
</button>
);
}
}
Button.contextTypes = {
color: React.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: React.PropTypes.string
};
通过给 如果没有定义 父子耦合Context可以构建API使得父组价和子组件进行相互通信。例如:React Router V4工作机制如下: import { BrowserRouter as Router,Route,Link } from 'react-router-dom';
const BasicExample = () => (
<Router> <div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> <li><Link to="/topics">Topics</Link></li> </ul> <hr /> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/topics" component={Topics} /> </div> </Router> );
通过从 在你构建包含类似于上述的API的组件之前,考虑是否有其他的更清晰的选择。例如,你可以传递整个React组件作为props传递。 在生命周期函数中使用
|