简体   繁体   English

在React.js的父组件中使用react-router时,如何使用react context API将数据从父组件传递到子组件?

[英]How do I use react context API to pass data from parent component to child component when using react-router in the parent component in React.js?

App.js - The parent component App.js-父组件

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';

import ChildComponent1 from './ChildComponent1';
import ChildComponent2 from './ChildComponent2';
import Context from './Context';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        messageThatllChange: "changing message",
    };
  }

  render() {
    return (
        <Router>
            <Switch>
                <Context.Provider value={this.state.messageThatllChange}>
                    <Route exact path='/' component={ChildComponent1} />
                    <Route path='/chat' component={ChildComponent2} />
                </Context.Provider>
            </Switch>
        </Router>
    );
  }
}

export default App;

ChildComponent1.js - child component ChildComponent1.js-子组件

import React from 'react';
import Context from './Context';

class Join extends React.Component {
    static contextType = Context;

    constructor(props) {
        super(props);
        console.log(this.context); // this.context returns undefined.
    }

    render() {
        return (
            <div>
                {/* Something important here */}
            </div>
        );
    }
}

// Join.contextType = Context; // tried this too
export default Join;

In the child component 1 constructor trying to print this.context returns undefined . 在子组件1的构造函数中,尝试打印this.context返回undefined

How do I pass the context from parent to children? 如何将上下文从父母传递给孩子? What am I doing wrong? 我究竟做错了什么?

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const Context = React.createContext({ message: "hi" });

class Child extends React.Component {
  constructor() {
    super();
    console.log("Constructor: ", this.context); // undefined here
  }
  render() {
    const message = this.context;
    return <p>{message}</p>; // hello here
  }
}

Child.contextType = Context;

function App() {
  return (
    <div className="App">
      <Context.Provider value="hello">
        <Child />
      </Context.Provider>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Trying to print the context in the constructor returns undefined, but you should be able to use context in the render function like this. 尝试在构造函数中打印上下文会返回未定义的内容,但是您应该能够像这样在render函数中使用上下文。

You can run the example here: https://codesandbox.io/s/crazy-forest-89bd6?fontsize=14 您可以在此处运行示例: https : //codesandbox.io/s/crazy-forest-89bd6?fontsize=14

Try to rewrite your child component like one of them below: 尝试像下面的其中之一一样重写子组件:

Dynamic Context 动态语境

import React from 'react';
import Context from './Context'; // Context here is the name you defined as Context = React.createContext();

class Join extends React.Component {
    render() {
        let props = this.props;
        let value = this.context;
        return (
            <div>
                {/* Something important here */}
            </div>
        );
    }
}

Join.contextType = Context; // Context here is the name you defined as Context = React.createContext();
export default Join;

Context.Consumer Context.Consumer

import React from 'react';
import { Consumer } from './Context'; // the path is where your context file is

class Join extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <Consumer>
            {value => (
                {/* Here you can retrieve your messageThatllChange */}
                <div>
                    {/* Something important here */}
                </div>
            )
            </Consumer>
        );
    }
}

export default Join;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 React.JS 中将数据从子组件传递到父组件? - How to pass data from child to parent component in React.JS? 如何在React.JS中将状态从子组件传递给父组件? - How to pass state from child component to parent in React.JS? 在 React.js 中如何将数据从子组件传递到父组件 - How to pass data from a child component to a parent component in React.js 如何通过道具[REACT.JS]将图片网址从父组件传递到子组件 - How can I pass image url from parent component to child component via props [REACT.JS] 在 REACT.js 中,如何将状态从子组件传递到父组件作为道具 - In REACT.js how can I pass a state from child component up to Parent component as a prop 当父组件向子组件传递数据并渲染子组件时显示加载栏。 反应.JS - show loading bar when parent component pass data to and render child component. React.JS 在React.js中从父组件调用子组件函数 - Calling Child component function from Parent component in React.js 在 React.js 中将 props 传递给父组件 - Pass props to parent component in React.js 将数据从子级传递到父级,再传递到另一个子级组件React Js - Pass data from child to parent and to another child component React Js 单击react-router Link时,如何将状态传输到父组件? - How do I transmit a state to a parent component when clicking a react-router Link?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM