Sla*_*lam 0 reactjs react-native react-hooks
我想编写 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>
);
}
Run Code Online (Sandbox Code Playgroud)
变更.js
import React from 'react';
export const Change = () => {
const [State, setState] = React.useState(0);
// Other hook work.
// The function returns nothing
};
Run Code Online (Sandbox Code Playgroud)
我的错误是什么?我该如何解决?
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>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5370 次 |
| 最近记录: |