【发布时间】:2019-08-26 21:47:50
【问题描述】:
我有一个可触摸的不透明度,里面有一些视图。我有一个特定的视图,我不希望它可以点击。我怎样才能做到这一点?
【问题讨论】:
-
你是说要根据条件禁用触摸事件?
-
@hongdevelop 是的
标签: react-native
我有一个可触摸的不透明度,里面有一些视图。我有一个特定的视图,我不希望它可以点击。我怎样才能做到这一点?
【问题讨论】:
标签: react-native
您不希望它可点击的特定视图应该是 "TouchableOpacity" 但具有 activeOpacity={1} 。这样,父 TouchableOpacity 将不起作用,activeOpacity={1} 将使其像禁用
完整代码
import React, { Component } from "react";
import { TouchableOpacity, View, Text } from "react-native";
export default class App extends Component {
render() {
return (
<View style={{ flex: 1, margin: 50 }}>
<TouchableOpacity
style={{ backgroundColor: "red", width: 250, height: 250 }}
>
<TouchableOpacity
style={{
backgroundColor: "green",
width: 100,
height: 100,
margin: 20,
alignItems: "center",
justifyContent: "center"
}}
activeOpacity={1}
>
<Text>No Click Area</Text>
</TouchableOpacity>
</TouchableOpacity>
</View>
);
}
}
应用预览
【讨论】:
【讨论】:
我不知道你在说什么条件,但是如果你想做你想做的事,你可以使用status 值。要在显示屏幕时停用按钮,请在渲染屏幕时更改 status 值,或在按下按钮时更改它。示例附在一起。
示例
import * as React from 'react';
import { Text, View, StyleSheet,TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
export default class App extends React.Component {
constructor(props){
super(props);
this.state={
disabled: false
}
}
componentDidMount(){
this.setState({ disabled: true})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a shareable url.
</Text>
<TouchableOpacity style={{width:"100%",height:20,alignItems:"center",backgroundColor:"blue"}} onPress={() => alert("touch")} disabled={this.state.disabled}>
<Text>Touch </Text>
</TouchableOpacity>
<TouchableOpacity style={{width:"100%",height:20,alignItems:"center",backgroundColor:"red"}} onPress={() => this.setState({disabled:true})}>
<Text>disabled</Text>
</TouchableOpacity>
</View>
);
}
}
【讨论】:
您可以这样做的另一种方法是使用 TouchableWithoutFeedback 包装您不想被点击的 View。
export default class App extends React.Component {
render() {
return (
<View style={{flex: 1, justifyContent: 'center'}}>
<TouchableOpacity style={{backgroundColor: "blue", width: 300, height: 300}}>
<TouchableWithoutFeedback>
<View style={{backgroundColor: "yellow", width: 100, height: 100}}>
<Text>Hello</Text>
</View>
</TouchableWithoutFeedback>
</TouchableOpacity>
</View>
);
}
}
【讨论】:
正如@AnaGard 建议的那样,在可按压容器内拥有press free 视图的关键是在没有 onPress 值的情况下制作可按压的内部视图。
比使用 TouchableOpacity 更好的是使用 Pressable 组件,ReactNative 的文档表明它更面向未来。
因此,这个问题的更新答案可能如下:
<View>
<Pressable
style={{ width: 500, height: 250 }}
onPress={() => onClose()}
>
<Pressable style={{ height: 100, width: 200 }}>
<View>
<Text>Your content here</Text>
</View>
</Pressable>
</Pressable>
</View>
一些参考资料:
【讨论】: