React Native 中使用 TypeScript 编写简单应用示例
以下是一个简单的 TypeScript 在 React Native 中的应用示例:
import React, { useState } from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
interface Props {
name: string;
}
const App: React.FC<Props> = ({ name }) => {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
return (
<View style={styles.container}>
<Text style={styles.text}>Hello, ' + name + '! </Text>
<Text style={styles.text}>Count: ' + count + '</Text>
<TouchableOpacity onPress={incrementCount} style={styles.button}>
<Text style={styles.buttonText}>Increment</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 24,
marginBottom: 12,
},
button: {
backgroundColor: '#007AFF',
padding: 12,
borderRadius: 4,
},
buttonText: {
color: '#fff',
fontWeight: 'bold',
fontSize: 18,
},
});
export default App;
这个示例中定义了一个名为 'App' 的函数组件,在组件的 props 中定义了一个 'name' 属性。组件内部使用了 'useState' Hook 来定义一个 'count' 状态,并在 'incrementCount' 函数中更新了状态。
组件的渲染部分包含了一个文本和一个按钮,按钮的点击事件绑定了 'incrementCount' 函数。样式使用了 'StyleSheet.create' 创建的样式表。
最后,使用 'export default' 导出组件。
原文地址: https://www.cveoy.top/t/topic/niBf 著作权归作者所有。请勿转载和采集!