用钩子在reactjs中传递函数的正确方法



你好,我有一个关于将函数传递给子函数的正确方法的问题基本上,在我的最高级别组件中,我有一个主题:

export default function App() {
const { theme, setTheme } = useAppTheme();
useEffect(() => {});
return (
<ThemeProvider theme={theme}>
<GlobalStyle />
<div className="App">
<Header />
</div>
</ThemeProvider>
);
}

这是我为获取和设置主题定制的挂钩:

export default function useAppTheme(defaultTheme = lightTheme) {
const [theme, _setTheme] = useState(getInitialTheme);
function getInitialTheme() {
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark' || savedTheme === 'light') {
return JSON.parse(savedTheme) === 'dark' ? darkTheme : defaultTheme;
} else {
return defaultTheme;
}
}
useEffect(() => {
localStorage.setItem('theme', JSON.stringify(theme.type));
}, [theme]);
return {
theme,
setTheme: ({ setTheme, ...theme }) => {
if (theme.type === 'dark') {
return _setTheme(darkTheme);
} else {
return _setTheme(lightTheme);
}
},
};
}

然后在我的组件标题中,我使用来自EMOTION主题的useTheme

const Header = () => {
const Theme = useTheme();
return (
<Container theme={Theme}>
<TopHeader theme={Theme} />
<NavBar theme={Theme} />
</Container>
);
};

然后我有一个组件,它是我的头的子组件,我需要我的setTheme函数来更改主题:

const ItemsTop = props => {
return (
<WrapperTop
justify={'space-between'}
align={'center'}
flexdirection={'row'}
>
<img src={LogoImg} />
<SearchContainer>
<div>
<FontAwesomeIcon
className="searchIcon"
icon={faSearch}
size="2x"
fixedWidth
color="white"
/>
</div>
<input placeholder="Pesquisar"></input>
</SearchContainer>
<AccessibilityTwo>
<FontAwesomeIcon
className="adjust"
icon={faAdjust}
size="1x"
fixedWidth
color="white"
/>
<FontAwesomeIcon
icon={faTextHeight}
size="1x"
fixedWidth
color="white"
/>
</AccessibilityTwo>
</WrapperTop>
);
};

因此,我想知道将setTheme函数从我的自定义挂钩传递给组件Header 的子级的正确方法是什么

我不知道你是如何使用ItemsTop组件的,但想象一下你在Header:中调用它

const Header = () => {
const Theme = useTheme();
return (
<Container theme={Theme}>
...
<ItemsTop setTheme={props.setTheme}/>
</Container>
);
};

上面的代码将函数setTheme传递给ItemsTop的props,但要使此函数出现在Headerprops中,您必须像一样传递它

export default function App() {
const { theme, setTheme } = useAppTheme();
useEffect(() => {});
return (
<ThemeProvider theme={theme}>
<GlobalStyle />
<div className="App">
<Header setTheme={setTheme} />
</div>
</ThemeProvider>
);
}

最后,您可以在ItemsTop访问道具中使用它:props.setTheme

相关内容

  • 没有找到相关文章

最新更新