【问题标题】:Can I use a React hook directly as a prop in JSX?我可以在 JSX 中直接使用 React 钩子作为道具吗?
【发布时间】:2020-08-21 17:47:02
【问题描述】:

我设法在没有来自 TSLint 的警告的情况下得到它。由于我正在大量重构应用程序,因此我要几天才能对其进行测试。

我从未见过 useCustomHook() 在教程或文档中直接传递提供者的值。写起来似乎简单多了。这是一种不好的做法,还是什么?

import useCustomHook, {customHookInitialValues, UseCustomHookType} from './useCustomHook'

export const Context = createContext<UseCustomHookType>({customHookInitialValues})

export const ContextProvider = ({ children }: Props) =>
  <Context.Provider value={useCustomHook()}>{children}</Context.Provider>

【问题讨论】:

  • 最好的做法是将它放在函数组件的顶部,但无论如何在这种情况下它应该可以正常工作。

标签: reactjs typescript react-native react-hooks react-context


【解决方案1】:

是的,你可以。

只要你尊重the rules of hooks。

这意味着你不能在循环(例如Array.prototype.map)或条件分支中使用它。

const darkStyles = { color: 'white', backgroundColor: 'black' };
const lightStyles = { color: 'black', backgroundColor: 'white' };
const errorStyles = { color: 'red', backgroundColor: 'white' };

// this is OK
export const MyComponent1: FunctionComponent = () => {
  const theme = useTheme();

  return <h1 style={useMemo(() => (theme.isDark ? darkStyles : lightStyles), [theme])}>My title</h1>;
};

// this NOT OK
export const MyComponent2: FunctionComponent = () => {
  const theme = useTheme();
  const auth = useAuth();

  return auth.isConnected ? (
    <h1 style={useMemo(() => (theme.isDark ? darkStyles : lightStyles), [theme])}>My title</h1>
  ) : (
    <h1 style={errorStyles}>Please log-in</h1>
  );
};

【讨论】:

    猜你喜欢
    • 2017-06-21
    • 1970-01-01
    • 2022-01-07
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2021-11-01
    • 2022-07-14
    相关资源
    最近更新 更多