我想撰寫 1 個常用函式,用于不同的功能組件。
這個通用函式使用鉤子,我得到錯誤:Error: Invalid hook call. Hooks can only be called inside the body of a functional component.
我的代碼示例:
應用程式.js
import React from 'react';
import {
Text,
TouchableOpacity,
} from 'react-native';
import { Change } from 'static/Change';
export default function App() {
return (
<TouchableOpacity
onPress={() => {
Change();
}}
>
<Text>Click Me!</Text>
</TouchableOpacity>
);
}
改變.js
import React from 'react';
export const Change = () => {
const [State, setState] = React.useState(0);
// Other hook work.
// The function returns nothing
};
我的錯誤是什么,我該如何解決?
uj5u.com熱心網友回復:
Hooks 有一些規則要遵循 - https://reactjs.org/docs/hooks-rules.html
重構代碼如下
import React from "react";
import { Text, TouchableOpacity } from "react-native";
function useChange() {
const [state, setState] = React.useState(0);
function change(value) {
setState(value);
}
return { change, state };
}
export default function App() {
const { change, state } = useChange();
return (
<TouchableOpacity
onPress={() => {
// Update state value on press
change(state 1);
}}
>
<Text>Click Me!{state}</Text>
</TouchableOpacity>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/445041.html
