javascript - 组件如何将 prop 传递给另一个组件?

标签 javascript reactjs

新手,正在研究documentationreactReact Context API ,有些东西我看不懂,后面的题目我看不懂就不会看懂。谁能帮我举个例子是什么意思?

The Toolbar component must take an extra "theme" prop
and pass it to the ThemedButton. This can become painful
if every single button in the app needs to know the theme
because it would have to be passed through all components.

class App extends React.Component {
  render() {
    return <Toolbar theme="dark" />;
  }
}

function Toolbar(props) {
  // The Toolbar component must take an extra "theme" prop
  // and pass it to the ThemedButton. This can become painful
  // if every single button in the app needs to know the theme
  // because it would have to be passed through all components.
  return (
    <div>
      <ThemedButton theme={props.theme} />
    </div>
  );
}

class ThemedButton extends React.Component {
  render() {
    return <Button theme={this.props.theme} />;
  }
}

The Toolbar component must take an extra "theme" prop

这可以像<Toolbar theme="dark">

and pass it to the ThemedButton

如何 Toolbar组件将此 Prop 传递给 ThemedButton ?并请澄清评论的其余部分。

谢谢你的帮助?你很善良

最佳答案

在你的Toolbar组件,它需要一个参数 props , props 是调用它时传递给它的任何属性,如 <Toolbar param1="someString" param2={someVariable}> ,在本例中为 props工具栏中的值将是一个对象,其中包含您作为键 = 值传递的数据,例如:{param1: "someString", param2: content_of_someVariable}

如果您实际上并不在工具栏中使用这些 Prop (属性)/参数,而是在子组件中使用,那么您必须再次将它们传递到另一个级别,例如 <ThemedButton theme={props.theme} /> ,然后 ThemedButton 本身最终将值传递给实际使用的组件,在您的情况下是:<Button theme={this.props.theme} />; .

因此,您必须将主题传递给多个组件,而这些组件根本不使用它或根本不关心它,只是为了将它传递给最终的 Button 组件。

(答案到此结束,下面是我努力以简单的方式解释上下文API)


为了避免烦人的关卡升级到另一个...,您可以使用上下文 API。因为每次你想在链中的最后一个中使用它时,跨 3-4 个以上的级别/组件传递一个值真的很失禁。

将上下文视为在根级别定义和导出的变量,并保存一些数据(例如用户登录状态或主题信息),无论何时您需要该数据,都可以导入并直接使用它.您使用您定义的上下文的 Provider 属性 (MyContext.Provider) 将数据分配给它,并使用 Consumer 属性 (MyContext.Consumer) 来使用/访问您在提供程序中分配的数据。

上下文消费者的美妙之处在于,无论何时数据在提供者中更新,消费者都会立即获取新数据并触发使用新数据的重新渲染。

我希望我能以简单明了的方式解释它。有任何问题或不清楚的地方写评论,我会尽力改进答案。

祝你好运!

关于javascript - 组件如何将 prop 传递给另一个组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58861051/

相关文章:

javascript - 将 Google 表格文档单元格设置为只读

javascript - 如果找不到数据,如何显示错误消息?

javascript - 使用 HTML & CSS & JS 创建流畅的全屏布局的最佳技术?

reactjs - React 路由器更改 url 但不更改 View (仅在 Internet Explorer 11 上)

javascript - 如何让 intro js 与 React 一起工作?

reactjs - 当我们可以使用 Provider、useDispatch()、useSelector() 来访问 store、dispatch 和其他重要的 React-Redux 东西时,为什么还要使用 connect() 呢?

javascript - 如何正确模拟 useLocation?

javascript - Cordova - ios - 在 map 应用程序中打开 - 未打开 - 'maps://?q='

javascript - 按“应用”按钮后,日期范围选择器时间选择器不应用

javascript - 从父组件调用子组件函数时,React Material-UI 抽屉不工作