简体   繁体   English

在不相关的组件之间反应上下文

[英]React context between unrelated components

For learning purposes I'm just trying to render this dumb example where Component A has a variable that creates a random number and another (unrelated) Component B can render it with useContext .出于学习目的,我只是想呈现这个愚蠢的示例,其中组件A有一个创建随机数的变量,另一个(不相关的)组件B可以使用useContext呈现它。 I don't know how to make the provider of the context to know that the value is the variable from Component A .我不知道如何让上下文的提供者知道该值是来自 Component A的变量。

I created another file to do the React.createContext() ... but still don't know how to make the random number to reach there or the App Component to do the Provider.我创建了另一个文件来执行React.createContext() ...但仍然不知道如何使随机数到达那里或App组件来执行提供程序。 I know I could create the random number in App component and provide whatever component I want with that value, but I just want the value to be generated in Component A and reach Component B .我知道我可以在App组件中创建随机数并使用该值提供我想要的任何组件,但我只想在组件A生成该值并到达组件B Any ideas?有任何想法吗? Maybe its so simple I can't see it.也许它太简单了我看不到它。

What I have at the moment:我目前所拥有的:

Component A:组件 A:

import React from'react';

export default function RandomNumGenerator() {

    const randomNum = Math.random();

    return(
        <h2>Your random number is:</h2>
    )
}

Component B:组分 B:

import React from'react';

export default function RandomNumRenderizator() {

    return(
        <h2></h2> //Want to render the random num here
    )
}

App Component:应用组件:

import React from 'react';

import RandomNumGenerator from "./FunctionalComponents/RandomNumGenerator/RandomNumGenerator";
import RandomNumRenderizator from "./FunctionalComponents/RandomNumRenderizator/RandomNumRenderizator";
import RandomNumContext from "./contexts/RandomNumContext";


export default function App() {

  return (
    <div>
      <RandomNumGenerator/>
      <RandomNumContext.Provider value={}> //Empty value as I don't know what to send
        <RandomNumRenderizator/>
      </RandomNumContext.Provider>
    </div>
  );
}

And the Context:和上下文:

import React from "react";
const RandomNumContext = React.createContext(); //Don't know if there should be anything as defaultValue
export default RandomNumContext;

As data flows down in React, the value you wish to pass have to be in scope with the context provider, then you just need to read the context value using a hook:数据在 React 中向下流动时,您希望传递的值必须在上下文提供程序的范围内,然后您只需要使用钩子读取上下文值:

export default function App() {
  const randomNum = Math.random();
  return (
    <>
      <RandomNumDisplay num={randomNum} />
      <RandomNumContext.Provider value={randomNum}>
        <RandomNumRenderizator />
      </RandomNumContext.Provider>
    </>
  );
}

export default function RandomNumRenderizator() {
  const randomNum = useContext(RandomNumContext);
  return <h2>{randomNum}</h2>;
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM