繁体   English   中英

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

[英]How does React Context work by using a function inside of 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

我正在尝试了解 React Context 内部结构,虽然很清楚如何使用 Context/Provider/Consumer 我只是似乎不明白这条线实际上是如何调用组件内部的函数的

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

是否可以在自定义组件中使用相同的模式? 这会引发警告“函数作为 React 子项无效。

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

React 函数作为子组件

因此,如果我做对了,您基本上是在问如何获得以下格式的组件:

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

这些被称为子函数。 您可以通过在本地管理组件中的状态或变量来实现,然后通过将子项实现MyComponent的函数,将该状态或变量传递给应用程序中的任何其他组件。

因此,您的MyComponent组件将如下所示:

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

这允许您在任何具有完全相同的状态或变量的地方重用MyComponent但您可以以不同的方式呈现它

您会在诸如react-final-form类的库中发现这种模式很多,其中库维护一个状态,用户可以“使用”该状态并以他们想要的任何方式呈现它。

您可以在此链接此链接中阅读更多相关信息。

了解 React Context 内部结构

React Context Consumer children 是一个函数,而不是典型的字符串或 React 元素

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

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

上面的代码将被转译为


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

您可以看到子项( props.children )是一个函数。

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

这段代码意味着您在<div>声明了一个函数。 (不再调用该函数)

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

此函数将在ThemeContext.ConsumerThemeContext.Consumer然后您的元素将呈现

我认为它更像是一个 javascript 问题,而不是一个特定的反应; 反应组件最终会变成一个函数; javascript 支持函数作为第一类,因此函数可以作为参数传递给其他函数(或作为值返回),因此组件和上下文 API 越高。 所以你的问题可以大致翻译成这个代码片段:

 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