React JS // 从一个组件编辑另一个组件的样式



我的目标是创建一个基本应用程序,允许我使用另一个组件的操作来更改一个组件的样式。

假设我有一个<Btn/>组件和一个<Box/>组件,当单击按钮时,我想更改框的背景颜色。<Btn/><Box/>具有<App/>的共同祖先,但在组件树中都处于不同的级别。

顺便说一句.js

import React from 'react'
function Btn() {
const handleClick = (e) => {
//...
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}
export default Btn

盒子.js

import React from 'react'
function Box() {
return (
<h1>
Hello World!
</h1>
);
}
export default Box

我不想使用道具钻孔(在<App/>组件中使用样式设置/获取功能(来实现这一点。我还故意省略了组件样式,因为我对最适合解决此问题的样式选项持开放态度。

最好的方法是什么?(如果合适,我愿意使用Context,Redux或其他库。

最简单的方法是使用上下文,因为您使用的是函数组件而不是类,因此您需要的文档是useContexthttps://reactjs.org/docs/hooks-reference.html#usecontext。您仍然必须在应用程序级别或在应用程序级别调用的组件中定义 prop 和 "setter" 函数,但使用上下文,您不必将 props 一直向下传递。

以他们为例并将其适应您的用例,会是这样的。(工作样本:https://codesandbox.io/s/stackoverflow-answer-7hryk(

const themes = {
light: {
foreground: "#000000",
background: "#eeeeee"
},
dark: {
foreground: "#ffffff",
background: "#222222"
}
};
const ThemeContext = React.createContext(themes.light);
function App() {
const [stateTheme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme: themes[stateTheme], setTheme: setStateTheme }}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar(props) {
return (
<div>
<ToggleButtons />
<ThemedButton />
</div>
);
}
function ToggleButtons() {
const { setTheme } = useContext(ThemeContext);
return (
<div>
<button onClick={() => setTheme('light')}>Light Theme</button>
<button onClick={() => setTheme('dark')}>Dark Theme</button>
</div>
);
}
function ThemedButton() {
const { theme } = useContext(ThemeContext);
return (
<button style={{ background: theme.background, color: theme.foreground }}>
I am styled by theme context!
</button>
);
}

最新更新