输入组件
在React Native中,输入组件主要用于用户与应用进行交互。常用的输入组件包括TextInput、Picker等。
TextInput
TextInput组件用于接收用户输入的文本信息。它支持多种属性来控制其行为和外观。
基本使用
// www.javascriptcn.com code example
import React, { Component } from 'react';
import { View, TextInput, StyleSheet } from 'react-native';
export default class App extends Component {
state = {
text: '',
};
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="请输入文字"
onChangeText={(text) => this.setState({ text })}
value={this.state.text}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
paddingHorizontal: 8,
},
});密码框
secureTextEntry属性可以用来隐藏输入的内容,常用于密码输入场景。
// www.javascriptcn.com code example
import React, { Component } from 'react';
import { View, TextInput, StyleSheet } from 'react-native';
export default class PasswordInput extends Component {
state = {
password: '',
};
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="请输入密码"
secureTextEntry={true}
onChangeText={(password) => this.setState({ password })}
value={this.state.password}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
paddingHorizontal: 8,
},
});输入限制
通过设置maxLength属性,可以限制用户输入的最大长度。
// www.javascriptcn.com code example
import React, { Component } from 'react';
import { View, TextInput, StyleSheet } from 'react-native';
export default class LimitedInput extends Component {
state = {
text: '',
};
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="请输入文字(最多20个字符)"
maxLength={20}
onChangeText={(text) => this.setState({ text })}
value={this.state.text}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
paddingHorizontal: 8,
},
});Picker
Picker组件用于创建下拉列表。用户可以从多个选项中选择一个或多个值。
单选
// www.javascriptcn.com code example
import React, { Component } from 'react';
import { View, Picker, StyleSheet } from 'react-native';
export default class DropdownMenu extends Component {
state = {
selectedValue: 'java',
};
render() {
return (
<View style={styles.container}>
<Picker
selectedValue={this.state.selectedValue}
onValueChange={(itemValue, itemIndex) =>
this.setState({ selectedValue: itemValue })
}>
<Picker.Item label="Java" value="java" />
<Picker.Item label="JavaScript" value="js" />
<Picker.Item label="Python" value="py" />
</Picker>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
});多选
多选功能需要自己实现,因为React Native的Picker组件不直接支持多选。可以通过监听用户操作并手动更新状态来实现。
// www.javascriptcn.com code example
import React, { Component } from 'react';
import { View, Picker, StyleSheet } from 'react-native';
export default class MultiSelectDropdown extends Component {
state = {
selectedValues: ['java', 'py'],
};
handleSelectionChange = (value) => {
const { selectedValues } = this.state;
if (selectedValues.includes(value)) {
this.setState({ selectedValues: selectedValues.filter((v) => v !== value) });
} else {
this.setState({ selectedValues: [...selectedValues, value] });
}
};
render() {
return (
<View style={styles.container}>
<Picker
selectedValue={this.state.selectedValues}
mode="dropdown"
multiple={true}
onValueChange={this.handleSelectionChange}>
<Picker.Item label="Java" value="java" />
<Picker.Item label="JavaScript" value="js" />
<Picker.Item label="Python" value="py" />
</Picker>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
});表单验证
表单验证是确保用户输入数据符合预期的重要步骤。可以通过自定义函数或使用第三方库如Formik或Yup来实现。
自定义验证函数
// www.javascriptcn.com code example
import React, { Component } from 'react';
import { View, TextInput, StyleSheet, Button } from 'react-native';
class FormComponent extends Component {
state = {
username: '',
password: '',
isFormValid: false,
};
validateForm = () => {
const { username, password } = this.state;
if (username.length > 3 && password.length >= 6) {
this.setState({ isFormValid: true });
} else {
this.setState({ isFormValid: false });
}
};
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="用户名"
onChangeText={(username) => this.setState({ username })}
value={this.state.username}
/>
<TextInput
style={styles.input}
placeholder="密码"
secureTextEntry={true}
onChangeText={(password) => this.setState({ password })}
value={this.state.password}
/>
<Button title="提交" onPress={this.validateForm} disabled={!this.state.isFormValid} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
paddingHorizontal: 8,
marginBottom: 12,
},
});
export default FormComponent;使用第三方库
Formik是一个流行的库,用于简化表单管理和验证。
首先安装formik和yup:
npm install formik yup
然后使用它们构建表单:
// www.javascriptcn.com code example
import React from 'react';
import { View, StyleSheet } from 'react-native';
import { Formik } from 'formik';
import * as Yup from 'yup';
const SignupSchema = Yup.object().shape({
username: Yup.string()
.min(4, '太短了')
.max(15, '太长了')
.required('必须填写'),
password: Yup.string()
.min(6, '密码太短')
.required('必须填写'),
});
const FormikExample = () => (
<View style={styles.container}>
<Formik
initialValues={{ username: '', password: '' }}
validationSchema={SignupSchema}
onSubmit={(values) => {
console.log(values);
}}>
{({
handleChange,
handleBlur,
handleSubmit,
values,
errors,
touched,
}) => (
<>
<TextInput
style={styles.input}
placeholder="用户名"
onChangeText={handleChange('username')}
onBlur={handleBlur('username')}
value={values.username}
/>
{touched.username && errors.username && (
<Text style={styles.error}>{errors.username}</Text>
)}
<TextInput
style={styles.input}
placeholder="密码"
secureTextEntry={true}
onChangeText={handleChange('password')}
onBlur={handleBlur('password')}
value={values.password}
/>
{touched.password && errors.password && (
<Text style={styles.error}>{errors.password}</Text>
)}
<Button title="提交" onPress={handleSubmit} />
</>
)}
</Formik>
</View>
);
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
paddingHorizontal: 8,
marginBottom: 12,
},
error: {
color: 'red',
fontSize: 12,
},
});
export default FormikExample;以上代码展示了如何使用React Native构建表单组件,并通过自定义验证函数和第三方库进行表单验证。希望这些示例能帮助你更好地理解和使用React Native中的表单组件。