简体   繁体   English

React Context 如何通过使用组件内部的函数来工作

[英]How does React Context work by using a function inside of a component

How does this code work ?这段代码是如何工作的? How can a function be called inside a component?如何在组件内部调用函数?

import React from 'react'

const ThemeContext = React.createContext('blue');

const App = () =>
    <ThemeContext.Provider value={'green'}>
        <ThemeContext.Consumer>
            {(value) => <button style={{ background: value }}>Hello Context!</button>}
        </ThemeContext.Consumer>
    </ThemeContext.Provider>

export default App

I am trying to understand React Context internals , While it is clear how Context/Provider/Consumer can be used I just don't seem to understand how this line actually works calling a function inside of a component我正在尝试了解 React Context 内部结构,虽然很清楚如何使用 Context/Provider/Consumer 我只是似乎不明白这条线实际上是如何调用组件内部的函数的

<ThemeContext.Consumer>
    {(value) => <button style={{ background: value }}>Hello Context!</button>}
</ThemeContext.Consumer>

Is it possible have the same pattern work inside of a custom component?是否可以在自定义组件中使用相同的模式? This throws a warning 'Functions are not valid as a React child.这会引发警告“函数作为 React 子项无效。

<div>
{(value)=><span>{value}</span>}
</div>

React Functions as Child Components React 函数作为子组件

So if I'm getting this right, you are basically asking how you could get a component which is in the following format:因此,如果我做对了,您基本上是在问如何获得以下格式的组件:

<MyComponent>
  {(name) => (
    <div>{name}</div>
  )}
</MyComponent>

These are called functions as children.这些被称为子函数。 You do it by managing the state or a variable in a component locally and you pass that state or variable to any other component in the app by implementing the children as a function in MyComponent .您可以通过在本地管理组件中的状态或变量来实现,然后通过将子项实现MyComponent的函数,将该状态或变量传递给应用程序中的任何其他组件。

So your MyComponent component will look something as follows:因此,您的MyComponent组件将如下所示:

class MyComponent extends React.Component { 
  render() {
    return (
      <div>
        {this.props.children('Scuba Steve')}
      </div>
    );
  }
}
MyComponent.propTypes = {
  children: React.PropTypes.func.isRequired,
};

This allows you to reuse MyComponent anywhere with the exact same state or variables but you could render it differently .这允许您在任何具有完全相同的状态或变量的地方重用MyComponent但您可以以不同的方式呈现它

You would find this pattern quite a lot in libraries like react-final-form for example, where the library maintains a state and the users can "consume" that state and render it in anyway they want.您会在诸如react-final-form类的库中发现这种模式很多,其中库维护一个状态,用户可以“使用”该状态并以他们想要的任何方式呈现它。

You can read more about it at this link and at this link as well .您可以在此链接此链接中阅读更多相关信息。

Understand React Context internals了解 React Context 内部结构

The React Context Consumer children is a function instead of typical string or React Element React Context Consumer children 是一个函数,而不是典型的字符串或 React 元素

<ThemeContext.Consumer>
  {(value) => <button style={{ background: value }}>Hello Context!</button>}
</ThemeContext.Consumer>

<div>
  Hey, I'm normal JSX
</div>

The above code will be transpiled to上面的代码将被转译为


React.createElement(ThemeContext.Consumer, null, function (value) {
    return React.createElement("button", {
      style: {
        background: value
      }
    }, "Hello Context!");
  })

React.createElement("div", null, "Hey, I'm normal JSX"))

You can see that the children ( props.children ) is a function.您可以看到子项( props.children )是一个函数。

<div>
   {(value)=><span>{value}</span>}
</div>

This code is mean that you declared a function inside <div> .这段代码意味着您在<div>声明了一个函数。 (Not calling that function any more) (不再调用该函数)

<ThemeContext.Consumer>
    {(value) => <button style={{ background: value }}>Hello Context!</button>}
</ThemeContext.Consumer>

This function will be called inside ThemeContext.Consumer then your element will render此函数将在ThemeContext.ConsumerThemeContext.Consumer然后您的元素将呈现

I see that it as more of a javascript question than a react specific;我认为它更像是一个 javascript 问题,而不是一个特定的反应; react components at the end the day will become a function;反应组件最终会变成一个函数; javascript support function as first-class, so a function can be passed to other function as arguments ( or returned as value ) hence the higher the components and context API. javascript 支持函数作为第一类,因此函数可以作为参数传递给其他函数(或作为值返回),因此组件和上下文 API 越高。 So your question can be roughly translated to this code snippet:所以你的问题可以大致翻译成这个代码片段:

 function Theme (color) { /* some code maybe */ return function Nav (TotalItems){ return `I'll render a ${color} with ${TotalItems} TotalItems`; } } let redThemed = Theme( "dark red"); let navComp = redThemed(17); console.log( navComp ); console.log( redThemed(12) ); let blueThemed = Theme( "light blue"); console.log( blueThemed(4) );

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

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