React Native中的用户输入收集与信息提示
在React Native开发中,收集用户输入和向用户展示信息是非常重要的功能。下面将详细介绍相关的组件和实现方法。
1. 收集用户输入的组件
在React Native里,有多种类似于网页表单元素的组件,用于收集用户输入:
-
文本输入框
:每个文本输入框都有对应的虚拟键盘,在使用时需要考虑这一点。
-
选择器组件(Picker)
:允许用户从选项列表中选择一个项目。
-
开关组件(Switch)
:类似于复选框。
-
日期/时间选择器
:可在iOS和Android系统上通用。
2. 信息的定义与使用原则
在实现警报、通知和确认功能之前,需要明确它们的定义和使用原则:
-
警报(Alert)
:表示重要事件发生,必须确保用户看到相关情况,可能需要用户确认。
-
通知(Notification)
:表示发生了某件事,但重要性不足以完全阻止用户当前的操作,通常会自动消失。
-
确认(Confirmation)
:是警报的一部分,例如用户执行操作后,在继续之前需要确认操作是否成功;也可用于警告用户即将执行的操作。
使用原则是:对于仅需知晓但非关键的信息,使用通知;只有当功能的工作流程必须得到用户确认才能继续时,才使用确认。
3. 获取用户确认
3.1 成功确认
当用户成功执行某个操作后,可以显示一个模态视图来让用户确认。以下是实现成功确认模态视图的代码:
import React, { PropTypes } from 'react';
import {
View,
Text,
Modal,
} from 'react-native';
import styles from './styles';
const ConfirmationModal = props => (
<Modal {...props}>
<View style={styles.modalContainer}>
<View style={styles.modalInner}>
<Text style={styles.modalText}>Dude, srsly?</Text>
<Text
style={styles.modalButton}
onPress={props.onPressConfirm}
>
Yep
</Text>
<Text
style={styles.modalButton}
onPress={props.onPressCancel}
>
Nope
</Text>
</View>
</View>
</Modal>
);
ConfirmationModal.propTypes = {
visible: PropTypes.bool.isRequired,
onPressConfirm: PropTypes.func.isRequired,
onPressCancel: PropTypes.func.isRequired,
};
ConfirmationModal.defaultProps = {
transparent: true,
onRequestClose: () => {},
};
export default ConfirmationModal;
模态视图的样式如下:
modalContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
modalInner: {
backgroundColor: 'azure',
padding: 20,
borderWidth: 1,
borderColor: 'lightsteelblue',
borderRadius: 2,
alignItems: 'center',
},
modalText: {
fontSize: 16,
margin: 5,
color: 'slategrey',
},
modalButton: {
fontWeight: 'bold',
margin: 5,
color: 'slategrey',
},
除了自定义模态视图,React Native还提供了类似网页浏览器中
alert()
函数的
Alert.alert()
方法。为了避免直接暴露这个命令式API,我们可以实现一个警报确认组件:
import React, { Component, PropTypes } from 'react';
import {
Alert,
} from 'react-native';
const actions = new Map([
[true, Alert.alert],
[false, () => {}],
]);
class ConfirmationAlert extends Component {
componentDidMount() {
actions.get(this.props.visible)(
this.props.title,
this.props.message,
this.props.buttons,
);
}
componentWillReceiveProps(props) {
actions.get(props.visible)(
props.title,
props.message,
props.buttons,
);
}
render() {
return null;
}
}
ConfirmationAlert.propTypes = {
visible: PropTypes.bool.isRequired,
title: PropTypes.string,
message: PropTypes.string,
buttons: PropTypes.array,
};
export default ConfirmationAlert;
以下是同时展示模态确认对话框和警报确认对话框的代码:
import React, { Component } from 'react';
import {
AppRegistry,
View,
Text,
} from 'react-native';
import { fromJS } from 'immutable';
import styles from './styles';
import ConfirmationModal from './ConfirmationModal';
import ConfirmationAlert from './ConfirmationAlert';
class SuccessConfirmation extends Component {
state = {
data: fromJS({
modalVisible: false,
alertVisible: false,
}),
}
get data() {
return this.state.data;
}
set data(data) {
this.setState({ data });
}
toggleModal = () => {
this.data = this.data
.update('modalVisible', v => !v);
}
toggleAlert = () => {
this.data = this.data
.update('alertVisible', v => !v);
}
render() {
const {
modalVisible,
alertVisible,
} = this.data.toJS();
const {
toggleModal,
toggleAlert,
} = this;
return (
<View style={styles.container}>
<ConfirmationModal
animationType="fade"
visible={modalVisible}
onPressConfirm={toggleModal}
onPressCancel={toggleModal}
/>
<ConfirmationAlert
message="For realz?"
visible={alertVisible}
buttons={[
{
text: 'Nope',
onPress: toggleAlert,
},
{
text: 'Yep',
onPress: toggleAlert,
},
]}
/>
<Text
style={styles.text}
onPress={toggleModal}
>
Show Confirmation Modal
</Text>
<Text
style={styles.text}
onPress={toggleAlert}
>
Show Confimation Alert
</Text>
</View>
);
}
}
AppRegistry.registerComponent(
'SuccessConfirmation',
() => SuccessConfirmation
);
3.2 错误确认
当需要用户确认错误时,前面提到的原则同样适用。如果需要更多的显示控制,可以使用模态视图。以下是创建错误确认模态视图的样式代码:
import { StyleSheet } from 'react-native';
export default StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'ghostwhite',
},
text: {
color: 'slategrey',
},
modalContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
modalInner: {
backgroundColor: 'azure',
padding: 20,
borderWidth: 1,
borderColor: 'lightsteelblue',
borderRadius: 2,
alignItems: 'center',
},
modalInnerError: {
backgroundColor: 'lightcoral',
borderColor: 'darkred',
},
modalText: {
fontSize: 16,
margin: 5,
color: 'slategrey',
},
modalTextError: {
fontSize: 18,
color: 'darkred',
},
modalButton: {
fontWeight: 'bold',
margin: 5,
color: 'slategrey',
},
modalButtonError: {
color: 'black',
},
});
以下是应用样式的错误模态组件代码:
import React, { PropTypes } from 'react';
import {
View,
Text,
Modal,
} from 'react-native';
import styles from './styles';
const innerViewStyle = [
styles.modalInner,
styles.modalInnerError,
];
const textStyle = [
styles.modalText,
styles.modalTextError,
];
const buttonStyle = [
styles.modalButton,
styles.modalButtonError,
];
const ErrorModal = props => (
<Modal {...props}>
<View style={styles.modalContainer}>
<View style={innerViewStyle}>
<Text style={textStyle}>
Epic fail!
</Text>
<Text
style={buttonStyle}
onPress={props.onPressConfirm}
>
Fix it
</Text>
<Text
style={buttonStyle}
onPress={props.onPressCancel}
>
Ignore it
</Text>
</View>
</View>
</Modal>
);
ErrorModal.propTypes = {
visible: PropTypes.bool.isRequired,
onPressConfirm: PropTypes.func.isRequired,
onPressCancel: PropTypes.func.isRequired,
};
ErrorModal.defaultProps = {
transparent: true,
onRequestClose: () => {},
};
export default ErrorModal;
4. 被动通知
前面介绍的通知都需要用户输入,而对于重要但忽略后不会产生重大影响的信息,可以使用被动通知。被动通知以不太干扰的方式显示,无需用户操作即可消失。
4.1 Android系统的被动通知
在Android系统中,可以使用Toast API实现被动通知,以下是实现代码:
import React, { PropTypes } from 'react';
import { ToastAndroid } from 'react-native';
import { Map as ImmutableMap } from 'immutable';
const show = (message, duration) => {
ToastAndroid.show(message, duration);
return null;
};
const Notification = ({ message, duration }) =>
ImmutableMap()
.set(null, null)
.set(undefined, null)
.get(message, show(message, duration));
Notification.propTypes = {
message: PropTypes.string,
duration: PropTypes.number.isRequired,
};
Notification.defaultProps = {
duration: ToastAndroid.LONG,
};
export default Notification;
4.2 iOS系统的被动通知
iOS系统的通知组件稍微复杂一些,需要使用状态和生命周期事件来使模态视图像临时通知一样工作,以下是代码实现:
import React, { Component, PropTypes } from 'react';
import {
View,
Modal,
Text,
} from 'react-native';
import { Map as ImmutableMap } from 'immutable';
import styles from './styles';
class Notification extends Component {
static propTypes = {
message: PropTypes.string,
duration: PropTypes.number.isRequired,
}
static defaultProps = {
duration: 1500,
}
state = { visible: false }
timer = null
showModal = (message, duration) => {
this.setState({
visible: ImmutableMap()
.set(null, false)
.set(undefined, false)
.get(message, true),
});
this.timer = ImmutableMap()
.set(null, () => null)
.set(undefined, () => null)
.get(message, () => setTimeout(
() => this.setState({ visible: false }),
duration
))();
}
componentWillMount() {
this.showModal(
this.props.message,
this.props.duration,
);
}
componentWillReceiveProps(props) {
this.showModal(
props.message,
props.duration,
);
}
componentWillUnmount() {
clearTimeout(this.timer);
}
render() {
const modalProps = {
animationType: 'fade',
transparent: true,
visible: this.state.visible,
};
return (
<Modal {...modalProps}>
<View style={styles.notificationContainer}>
<View style={styles.notificationInner}>
<Text>{this.props.message}</Text>
</View>
</View>
</Modal>
);
}
}
Notification.propTypes = {
message: PropTypes.string,
duration: PropTypes.number.isRequired,
};
Notification.defaultProps = {
duration: 1500,
};
export default Notification;
以下是主应用视图的代码:
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
} from 'react-native';
import { fromJS } from 'immutable';
import styles from './styles';
import Notification from './Notification';
class PassiveNotifications extends Component {
state = {
data: fromJS({
count: 0,
message: null,
}),
}
get data() {
return this.state.data;
}
set data(data) {
this.setState({ data });
}
render() {
const {
count,
message,
} = this.data.toJS();
return (
<View style={styles.container}>
<Notification message={message} />
<Text
onPress={() => {
this.data = this.data
.update('count', c => c + 1)
.set('message', null);
}}
>
Pressed {count}
</Text>
<Text
onPress={() => {
this.data = this.data
.set('message', 'Something happened!');
}}
>
Show Notification
</Text>
</View>
);
}
}
AppRegistry.registerComponent(
'PassiveNotifications',
() => PassiveNotifications
);
需要注意的是,即使
Notification
组件是声明式的,在更改其他状态值时,仍需将消息状态设置为
null
,否则重新渲染组件时会重复显示相同的通知。
总结
通过上述介绍,我们了解了React Native中收集用户输入的组件,以及如何使用警报、确认和被动通知向用户展示信息。在实际开发中,应根据信息的重要性和使用场景,合理选择合适的组件和方式。
以下是一个简单的流程图,展示信息提示的选择逻辑:
graph TD;
A[信息重要吗?] -->|是| B[需要用户确认吗?];
A -->|否| C[使用被动通知];
B -->|是| D[使用警报或模态确认];
B -->|否| C;
同时,为了更清晰地对比不同组件的特点,我们列出以下表格:
| 组件类型 | 重要性 | 是否需要用户操作 | 适用场景 |
| ---- | ---- | ---- | ---- |
| 警报 | 高 | 可能需要 | 重要事件通知,确保用户知晓 |
| 通知 | 中 | 否 | 重要但可忽略的信息 |
| 确认 | 高 | 需要 | 操作结果确认,流程继续依赖用户确认 |
| 被动通知 | 低 | 否 | 不太重要的信息提示 |
React Native中的用户输入收集与信息提示(续)
5. 各组件的使用场景分析
为了更合理地使用上述介绍的组件,下面详细分析它们在不同场景下的应用。
5.1 警报(Alert)
警报适用于需要用户立即关注的重要信息。例如,当用户在进行敏感操作(如删除重要数据、进行大额支付等)时,使用警报可以确保用户清楚了解操作的后果。以下是一个可能的使用流程:
1. 用户触发敏感操作。
2. 系统检测到操作并判断为敏感操作。
3. 调用警报组件(如
ConfirmationAlert
)显示提示信息,告知用户操作的风险和后果。
4. 用户确认操作或取消操作。
5. 系统根据用户的选择执行相应的操作。
5.2 确认(Confirmation)
确认通常用于操作结果的反馈和流程的控制。比如,当用户提交表单后,需要确认操作是否成功,或者在执行某些不可逆操作前,需要用户确认是否继续。使用确认组件(如
ConfirmationModal
)的步骤如下:
1. 用户执行操作。
2. 系统处理操作并返回结果。
3. 根据操作结果,显示相应的确认模态视图。
4. 用户确认信息,模态视图关闭。
5. 系统根据用户的确认继续后续流程。
5.3 被动通知(Notification)
被动通知适用于不需要用户立即响应的信息。例如,当有新消息提醒、系统更新提示等情况时,可以使用被动通知。以主应用视图代码中的
PassiveNotifications
组件为例,使用被动通知的步骤如下:
1. 系统检测到有需要通知的事件发生。
2. 更新状态中的
message
值,触发
Notification
组件显示通知。
3. 通知在一定时间后自动消失。
4. 如果需要再次显示通知,重复步骤2。
6. 代码优化建议
在实际开发中,为了提高代码的可维护性和性能,可以对上述代码进行一些优化。
6.1 组件复用
可以将一些通用的样式和逻辑提取到单独的组件中,以实现组件的复用。例如,将模态视图的公共样式和逻辑提取到一个基础模态组件中,然后在
ConfirmationModal
和
ErrorModal
中继承和扩展。以下是一个简单的示例:
import React, { PropTypes } from 'react';
import {
View,
Text,
Modal,
} from 'react-native';
import styles from './styles';
const BaseModal = props => (
<Modal {...props}>
<View style={styles.modalContainer}>
<View style={styles.modalInner}>
{props.children}
</View>
</View>
</Modal>
);
BaseModal.propTypes = {
visible: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
};
BaseModal.defaultProps = {
transparent: true,
onRequestClose: () => {},
};
export default BaseModal;
然后,
ConfirmationModal
和
ErrorModal
可以这样实现:
import React, { PropTypes } from 'react';
import BaseModal from './BaseModal';
import styles from './styles';
const ConfirmationModal = props => (
<BaseModal {...props}>
<Text style={styles.modalText}>Dude, srsly?</Text>
<Text
style={styles.modalButton}
onPress={props.onPressConfirm}
>
Yep
</Text>
<Text
style={styles.modalButton}
onPress={props.onPressCancel}
>
Nope
</Text>
</BaseModal>
);
ConfirmationModal.propTypes = {
visible: PropTypes.bool.isRequired,
onPressConfirm: PropTypes.func.isRequired,
onPressCancel: PropTypes.func.isRequired,
};
export default ConfirmationModal;
const ErrorModal = props => (
<BaseModal {...props}>
<Text style={[styles.modalText, styles.modalTextError]}>
Epic fail!
</Text>
<Text
style={[styles.modalButton, styles.modalButtonError]}
onPress={props.onPressConfirm}
>
Fix it
</Text>
<Text
style={[styles.modalButton, styles.modalButtonError]}
onPress={props.onPressCancel}
>
Ignore it
</Text>
</BaseModal>
);
ErrorModal.propTypes = {
visible: PropTypes.bool.isRequired,
onPressConfirm: PropTypes.func.isRequired,
onPressCancel: PropTypes.func.isRequired,
};
export default ErrorModal;
6.2 状态管理优化
使用更高效的状态管理库(如Redux、MobX等)可以更好地管理应用的状态。例如,在
PassiveNotifications
组件中,可以使用Redux来管理
count
和
message
状态,这样可以使状态的更新和传递更加清晰和可预测。
7. 兼容性考虑
在不同的操作系统(如iOS和Android)上,组件的显示效果和行为可能会有所不同。因此,在开发过程中需要进行充分的测试和适配。
7.1 样式适配
不同操作系统的默认样式可能不同,需要根据实际情况进行调整。例如,在iOS和Android上,模态视图的默认样式可能存在差异,可以通过自定义样式来统一显示效果。
7.2 API差异
不同操作系统可能提供不同的API,如Android的Toast API和iOS的模态视图实现方式不同。在开发被动通知组件时,需要根据不同的操作系统选择合适的API,以确保通知的正常显示。
总结回顾
本文全面介绍了React Native中收集用户输入的组件,以及如何使用警报、确认和被动通知向用户展示信息。通过详细的代码示例和使用场景分析,我们了解了各组件的特点和适用范围。在实际开发中,应根据信息的重要性和使用场景,合理选择合适的组件和方式。同时,为了提高代码的可维护性和性能,还可以进行组件复用和状态管理优化。
以下是一个总结性的流程图,展示整个信息处理和提示的流程:
graph LR;
A[用户操作] --> B[系统处理];
B --> C{信息重要性判断};
C -->|重要| D{是否需要确认};
C -->|不重要| E[被动通知];
D -->|需要| F[警报或模态确认];
D -->|不需要| E;
F --> G[用户确认操作];
G --> H[系统继续流程];
E --> I[通知自动消失];
为了更直观地对比不同信息提示方式的特点,我们再次列出以下表格:
| 提示方式 | 重要性级别 | 用户操作需求 | 显示形式 | 适用场景 |
| ---- | ---- | ---- | ---- | ---- |
| 警报 | 高 | 可能需要确认 | 弹出窗口 | 重要事件、风险提示 |
| 确认 | 高 | 需要确认 | 模态视图 | 操作结果反馈、流程控制 |
| 被动通知 | 低 | 无需操作 | 临时提示 | 新消息提醒、系统更新提示 |
通过合理运用这些信息提示方式,可以提升用户体验,确保用户能够及时、准确地获取重要信息。在未来的React Native开发中,希望大家能够根据实际需求,灵活选择和使用这些组件和技术。
超级会员免费看
308

被折叠的 条评论
为什么被折叠?



