我正在尝试实现一个基本的抽屉,但我对文档感到困惑.
有一个TouchableHighlight,还有一个TouchableNativeFeedback.
TouchableNativeFeedback仅适用于Android.那么,我怎样才能最好地处理我的MenuItem组件,以便它同时处理Android和IOS?
这是我到目前为止所得到的,我不知道如何在这里处理不同平台特定的可触摸内容:
import React, { Component, PropTypes } from 'react';
import { TouchableHighlight, TouchableNativeFeedback, Platform, View, Text } from 'react-native';
export class MenuItem extends Component {
handleAndroid() {
}
handleIOS() {
}
renderMenuItem() {
return (
<View style={styles.container}>
<Text style={styles.text}>
{this.props.text}
</Text>
</View>
);
}
render() {
return (
);
}
}
Run Code Online (Sandbox Code Playgroud)
在Android上,我是否只能使用TouchableNativeFeedback?
Gio*_*gos 22
就像你说的那样,TouchableNativeFeedbackAndroid只是因为它不适用于iOS.如果您想要一个适用于两者的解决方案,请相应地使用TouchableHighlight和设置样式.例如,它的underlayColor道具允许您设置"触摸激活时将显示的底衬的颜色".
编辑:
如果您想TouchableNativeFeedback用于Android和TouchableHighlightiOS,您应该执行以下操作:
import { Platform } from 'react-native'
...
render() {
if (Platform.OS === 'android') {
return (
<TouchableNativeFeedback>
...
</TouchableNativeFeedback>
)
} else {
return (
<TouchableHighlight>
...
</TouchableHighlight>
)
}
}
Run Code Online (Sandbox Code Playgroud)
编辑2:
或者,您可以为每个平台创建自定义组件并使用文件扩展名.例如:
MyButton.ios.js
MyButton.android.js
Run Code Online (Sandbox Code Playgroud)
将这两个放在同一个文件夹中,然后MyButton用作常规组件:
import MyButton from '../path/to/component/MyButton'
...
render() {
<MyButton/>
}
Run Code Online (Sandbox Code Playgroud)
如果要在多个位置使用此组件,这非常简洁,因为您没有使用if-else块填充代码.
在这里,您可以阅读有关Platform Specific Code的更多信息.
您可以像这样以更优雅的方式解决此问题:
render() {
let TouchablePlatformSpecific = Platform.OS === 'ios' ?
TouchableOpacity :
TouchableNativeFeedback;
let touchableStyle = Platform.OS === 'ios' ?
styles.iosTouchable :
styles.androidTouchable
return(
<TouchablePlatformSpecific style={touchableStyle}>
(...)
</TouchablePlatformSpecific>
);
}
Run Code Online (Sandbox Code Playgroud)
我一直在成功地使用它,但我看不出它不起作用的原因,它对我来说看起来不错。
小智 5
一个更好的实现是使用愚蠢的组件来生成通用的 Touchable,该组件根据平台工作并处理 onPress 事件。
可触摸组件:
import { Platform } from "react-native"
import { TouchableNativeFeedback, TouchableOpacity } from "react-native"
import React from "react"
export const Touchable = (props: any) => {
return Platform.OS === 'android'
? <TouchableNativeFeedback onPress={props.onPress}>{props.children}</TouchableNativeFeedback>
: <TouchableOpacity onPress={props.onPress}>{props.children}</TouchableOpacity>
}
Run Code Online (Sandbox Code Playgroud)
用法:
import { Touchable } from '../path/to/touchable.component';
...
render() {
<Touchable onPress={() => this.handleClick()}>
.....
</Touchable>
}
Run Code Online (Sandbox Code Playgroud)
感谢 @Giorgos 的实现,它构成了这个答案的基础。
| 归档时间: |
|
| 查看次数: |
7437 次 |
| 最近记录: |