Reactjs 如何处理React中的道具和紧密耦合组件?

Reactjs 如何处理React中的道具和紧密耦合组件?,reactjs,Reactjs,我有一对相互紧密耦合的组件。最高组件接收名为选项的属性。道具选项通过下一个组件传递,依此类推 从嵌套组件向其他组件发出更改的最佳方式是什么?在这种情况下,我不想使用redux。此示例适用于React16.3及更高版本 检查工作示例 a) 使用react的上下文api从父组件获取数据到嵌套的chid组件 1。总母公司组成部分 function ThemedButton(props) { // Use a Consumer to read the current theme context.

我有一对相互紧密耦合的组件。最高组件接收名为
选项的属性。道具
选项
通过下一个组件传递,依此类推


从嵌套组件向其他组件发出更改的最佳方式是什么?在这种情况下,我不想使用redux。

此示例适用于React16.3及更高版本

检查工作示例

a) 使用react的上下文api从父组件获取数据到嵌套的chid组件 1。总母公司组成部分

function ThemedButton(props) {
  // Use a Consumer to read the current theme context.
  // React will find the closest theme Provider above and use its value.
  // In this example, the current theme is "dark".
  return (
    <ThemeContext.Consumer>
      {theme => <div>{theme}</div>}
    </ThemeContext.Consumer>
  );
}
上下文允许我们将值传递到组件树的深处,而无需 通过每个组件显式地将其线程化。为创建上下文 当前主题(默认为“灯光”)

在这里,您正在从状态连接您的组件


您可以使用React或Redux的
context
。问题是什么?上下文如何解决我的问题?@siwymilek:-如果您使用react 16.3,这将解决您的问题。在下面的版本中,它将以不同的方式工作。你使用的是哪个版本。不完全是——它只有一种工作方式,即传递道具。无论如何,我决定在上下文中使用redux。在我的最高组件中,我订阅存储并覆盖上下文值。@siwymilek首先,如果您使用的是redux,则无需使用react的上下文api。一种使用内容的方法是,从最上面的组件传递道具,并且可以在子组件或嵌套子组件中获取道具。另一种是使用redux,因为您可以分派操作并存储数据,然后您可以使用react redux中的“connect”方法来获取存储数据。我有意识地使用了上下文api–这是一种比通过许多组件传递道具更好的解决方案。。。没有理由把所有这些联系起来components@siwymilek正如您所说的,您重写了上下文值,现在我添加了代码,让redux使用react redux的connect方法从存储中获取数据,以获取选项数据
function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}
function ThemedButton(props) {
  // Use a Consumer to read the current theme context.
  // React will find the closest theme Provider above and use its value.
  // In this example, the current theme is "dark".
  return (
    <ThemeContext.Consumer>
      {theme => <div>{theme}</div>}
    </ThemeContext.Consumer>
  );
}
const mapStateToProps = (state) => ({
  options: state.options,
});
export default connect(
  mapStateToProps,
  null,
)(ChildComponent);