我正在学习 React Native,一直收到此错误setState 不是 React Native 中的函数 我搜索了很多,但没有足够的帮助。
我创建了这个简化的代码来显示问题
import React, { useState } from "react";
import { Text, View, Button } from "react-native";
const Test = ({ Test1 }) => {
return (
<Button
onPress={() => {
Test1.setState(true);
}}
/>
);
};
const Test1 = () => {
const [state, setState] = useState(false);
if (state) {
return <Text>Test Working</Text>;
} else {
return <Text>Test Not Working</Text>;
}
};
const App = () => {
return (
<View>
<Test Test1={Test1} />
</View>
);
};
export default App;
这是错误:TypeError:Test1.setState 不是函数
请帮我解决这个问题。
最佳答案
状态只能作为 props 转移到其他组件。您需要从 App 中调用 Test1 组件,并从 Test1 中调用 Test 组件,然后您可以将 Test1 中的 props 传递给 Test。这样您就不需要将状态移动到其他组件。您不能将任何组件作为 props 传递并从那里访问状态或方法。您可以尝试以下代码:
import React, { useState } from "react";
import { Text, View, Button } from "react-native";
const Test = ({ setState}) => {
return (
<Button
onPress={() => {
setState(true);
}}
/>
);
};
const Test1 = () => {
const [state, setState] = useState(false);
if (state) {
return <Text>Test Working</Text>;
} else {
return <Test setState={setState} />;
}
};
const App = () => {
return (
<View>
<Test1 />
</View>
);
};
export default App;
关于javascript - setState 不是 React Native 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69490436/