簡體   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-父組件

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-子組件

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;

在子組件1的構造函數中,嘗試打印this.context返回undefined

如何將上下文從父母傳遞給孩子? 我究竟做錯了什么?

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);

嘗試在構造函數中打印上下文會返回未定義的內容,但是您應該能夠像這樣在render函數中使用上下文。

您可以在此處運行示例: https : //codesandbox.io/s/crazy-forest-89bd6?fontsize=14

嘗試像下面的其中之一一樣重寫子組件:

動態語境

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

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM