ReactNative快速入门
处理文本输入
TextInput
是一个允许用户输入文本的基础组件。它有一个onChangeText
函数属性,此属性会在文本变化时被调用。还有一个onSubmitEditing
属性,会在文本被提交后(用户按下软键盘上的提交键)调用。
假如我们要实现当用户输入时,实时将其以单词为单位翻译为另一种文字。一个单词翻译成一个 🍕。所以"Hello there ioser"将会被翻译为"🍕🍕🍕"。
TextInput示例
import React, { useState } from 'react';
import { SafeAreaView, Text, TextInput, View } from 'react-native';
const App = () => {
const [text, setText] = useState('');
return (
<SafeAreaView>
<View style={{ padding: 10 }}>
<TextInput
style={{ height: 40 }}
placeholder="Type here to translate!"
onChangeText={text => setText(text)}
onSubmitEditing={() => setText('submit')}
defaultValue={text}
/>
<Text style={{ padding: 10, fontSize: 42 }}>
{text.split(' ').map((word) => word && '🍕').join(' ')}
</Text>
<Image source={{
uri: 'https://reactnative.dev/img/tiny_logo.png',
width: 64,
height: 64
}}></Image>
</View>
</SafeAreaView>
);
}
export default App;
在上面的例子里,我们把text保存到 state 中,因为它会随着时间变化。上面的例子中顺便演示了下Image组件的用法。
使用滚动视图
滚动视图
ScrollView是一个通用的可滚动的容器,你可以在其中放入多个组件和视图。ScrollView 不仅可以垂直滚动,还能水平滚动(通过horizontal属性来设置)。
import React from 'react';
import { Image, SafeAreaView, ScrollView, Text } from 'react-native';
const logo = {
uri: 'https://reactnative.dev/img/tiny_logo.png',
width: 64,
height: 64
};
const App = () => (
<SafeAreaView>
<ScrollView>
<Text style={{ fontSize: 96 }}>Scroll me plz</Text>
<Image source={logo} />
<Image source={logo} />
<Text style={{ fontSize: 96 }}>If you like</Text>
<Image source={logo} />
<Image source={logo} />
<Image source={logo} />
<Text style={{ fontSize: 96 }}>Scrolling down</Text>
<Image source={logo} />
<Image source={logo} />
<Image source={logo} />
<Image source={logo} />
<Image source={logo} />
<Text style={{ fontSize: 96 }}>What's the best</Text>
<Image source={logo} />
<Image source={logo} />
<Text style={{ fontSize: 96 }}>Framework around?</Text>
<Image source={logo} />
<Image source={logo} />
<Image source={logo} />
<Image source={logo} />
<Image source={logo} />
<Text style={{ fontSize: 80 }}>React Native</Text>
</ScrollView>
</SafeAreaView>
);
export default App;
知识拓展
对上述示例进行扩展,将Text和Image都封装成一个组件。了解即可
了解组件封装
function MyImage() {
return <Image source={logo} />
}
const MyText: React.FC<{ children: React.ReactNode }> = ({ children }) => (
<Text style={{ fontSize: 56 }}>
{children}
</Text>
);
function MyText2({ children }: {children: React.ReactNode} ) {
return <Text style={{ fontSize: 56 }}>{children}</Text>
}
左右滚动
<ScrollView horizontal>