反应文档上下文示例



React docs 有以下示例 (https://reactjs.org/docs/context.html#parent-child-coupling(:

上下文还可以让你构建一个 API,其中父母和孩子 沟通。例如,一个以这种方式工作的库是 React 路由器 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>
);

但实际的例子在哪里?这段代码的哪一部分显示了使用 context 的示例?

它是

Router组件。您可以在此处查看代码。特别

getChildContext() {
  return {
    router: {
      ...this.context.router,
      history: this.props.history,
      route: {
        location: this.props.history.location,
        match: this.state.match
      }
    }
  };
}

以及孩子从树上传下来的render方法

render() {
  const { children } = this.props;
  return children ? React.Children.only(children) : null;
}

最新更新