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

时间:2020-02-18 22:08:02

标签: reactjs react-hooks

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

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的子级的正确方法是什么

1 个答案:

答案 0 :(得分:1)

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

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

上面的代码将函数setTheme传递给ItemsTop的道具,但是要使此函数出现在props的{​​{1}}中,您必须传递它像:

Header

最后,您可以在export default function App() { const { theme, setTheme } = useAppTheme(); useEffect(() => {}); return ( <ThemeProvider theme={theme}> <GlobalStyle /> <div className="App"> <Header setTheme={setTheme} /> </div> </ThemeProvider> ); } 中使用它来访问道具:ItemsTop