我可以直接使用 React hook 作为 JSX 中的 prop 吗?
Can I use a React hook directly as a prop in JSX?
我设法在没有来自 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>
是的,你可以。
只要你尊重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>
);
};
我设法在没有来自 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>
是的,你可以。
只要你尊重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>
);
};