reactjs - React 中的 props 和紧耦合组件如何处理?
问题描述
我有几个相互紧密耦合的组件。最高组件接收名为options
. 道具options
通过下一个组件传递,依此类推。
从嵌套组件向彼此发出更改的最佳方式是什么?在这种情况下,我宁愿不使用 redux。
解决方案
此示例适用于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);
推荐阅读
- php - 如何在 Laravel 中循环引导模式?
- javascript - 如何使用 grunt 更改我的 HTML 文件以引用我缩小的 JS 和 CSS 而不是未压缩的?
- css - 如何在 Blogger 博客中的菜单项周围创建边框?
- amazon-web-services - 上传文件后 AWS S3 隐藏标志丢失
- python - Tkinter - Spinbox 看起来比预期的要长
- python-3.x - 使用散景为图例添加值
- angular - 静态注入器错误
- regex - 如果存在两个或更多括号字符串,如何提取单元格末尾括号中分隔的字符串
- c - 在c中发送电子邮件,服务器在我发送正文后从不回复
- hibernate - Grails 3:GenericJDBCException:无法准备语句