首页 > 解决方案 > React 中的 props 和紧耦合组件如何处理?

问题描述

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

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

标签: reactjs

解决方案


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

单击此处查看工作示例。

a) 使用 react 的上下文 api 从父组件获取数据到嵌套的 chid 组件

1.祖父组件

Context 允许我们将一个值传递到组件树的深处,而无需显式地将其贯穿每个组件。为当前主题创建一个上下文(默认为“light”)。

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

class App extends React.Component {
  render() {
    // Use a Provider to pass the current theme to the tree below.
    // Any component can read it, no matter how deep it is.
    // In this example, we're passing "dark" as the current value.
    const theme = "dark";
    return (
      <ThemeContext.Provider value={theme}>
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

2.父组件

中间的组件不再需要明确地传递主题。

function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

3. 子组件

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 doc。点击这里

b)使用redux将数据从父组件存储并存储到嵌套的子组件中

在这里,您从状态中获取数据并将选项数据传递给您的组件

const mapStateToProps = (state) => ({
  options: state.options,
});

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

export default connect(
  mapStateToProps,
  null,
)(ChildComponent);

推荐阅读