gpt4 book ai didi

javascript - 在 onPress 上使用时 this.setState 不是一个函数

转载 作者:行者123 更新时间:2023-12-02 23:03:49 26 4
gpt4 key购买 nike

我对 React Native 相当陌生,当未定义的错误触发时,我正在为自己开发一个应用程序。

像我们大多数人一样,我用谷歌搜索了一下可能是什么问题,这似乎是一个常见问题,但没有解决办法。我尝试了箭头函数和 .bind 但似乎没有任何效果。

import React, {Fragment} from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
TouchableWithoutFeedback,
Button,
} from 'react-native';
//I'll use the other things I've imported later :-)

const App = () => {
state = {text: 'Hello World'};

return (
<View>
<Text style={styles.titleStyle}>Title Text</Text>

<TouchableWithoutFeedback
onPress={() => (this.setState({
text: 'Goodbye World',
}))}>
<View style={styles.physView}>
<Text style={styles.physTitle}>More Text</Text>
<Text style={styles.physText}>{this.state.text}</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
};

目标只是在按下时将文本更改为再见世界,但 setState 不是函数错误。最终,我想让“Hello World”和“Goodbye World”在点击时切换回来和第四个,但我还没有完全克服这个错误。

提前致谢,是的,这是虚拟文本。

最佳答案

您使用带有状态的功能组件。它不是那样工作的。功能组件不能有 setState 方法。

有两个选项:

// Use class syntax

class App extends React.Component {
constructor(props) {
super(props);

this.state = {
text: 'Hello world!',
}
}

onPress = () => {
this.setState({text: 'Bye-bye'});
}

render() {

return (
<View>
<Text style={styles.titleStyle}>Title Text</Text>

<TouchableWithoutFeedback
onPress={this.onPress}>
<View style={styles.physView}>
<Text style={styles.physTitle}>More Text</Text>
<Text style={styles.physText}>{this.state.text}</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
}
};

// Use hooks

import {useState} from 'react'

const App = () => {

const [text, setText] = useState('Hello World');

return (
<View>
<Text style={styles.titleStyle}>Title Text</Text>

<TouchableWithoutFeedback
onPress={() => setText('Goodbye World');}>
<View style={styles.physView}>
<Text style={styles.physTitle}>More Text</Text>
<Text style={styles.physText}>{this.state.text}</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
};

关于javascript - 在 onPress 上使用时 this.setState 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57680546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com