react-native - 如何同时处理视图和按钮的点击?
问题描述
好的,所以我想知道是否可以同时处理单击按钮和覆盖视图(触发按钮和 View/TouchableHighlight 的 onPress)
因为不可能仅将两个对象放在另一个之上,因为它只会使较高的对象(在 zIndex 上)可点击,但绝不会同时使两个对象可点击。
https://prntscr.com/p80uhl “应用程序视图”
https://prntscr.com/p80uj9 “组件的 zIndex”
https://prntscr.com/p814jm “React Native 页面截图”(代码结果)
代码:(我删除了一些功能以显示重要的)
// ... Imports
export default class TableConfig extends Component {
state = {
selected: -1,
// Other States
}
select = id => {
console.log('SELECTED: '+id);
//Change Selected and the Text
this.setState(() => ({ selected: id, selectedText: this.state.blocks[id].text }));
}
unselect = () => {
console.log('UNSELECTED!');
//Change State & Hide Component
this.setState(()=>{});
}
render(){
const { option } = this.state;
let select = this.select;
return(
<View style={styles.container}>
{ /* The Overlay */ }
<TouchableHighlight style={styles.full} onPress={()=>{this.unselect}}/>
{ /* That a Table of Buttons Basically (A grid of 2x2 Buttons) */ }
<Card flat style={styles.all}>
<View style={styles.row}>
<TableBlock text={this.state.blocks[0].text} color={this.state.blocks[0].color} icon={this.state.blocks[0].icon} onClick={() => {select(0)}}/>
<TableBlock text={this.state.blocks[1].text} color={this.state.blocks[1].color} icon={this.state.blocks[1].icon} onClick={() => {select(1)}}/>
</View>
<View style={styles.row}>
<TableBlock text={this.state.blocks[2].text} color={this.state.blocks[2].color} icon={this.state.blocks[2].icon} onClick={() => {select(2)}}/>
<TableBlock text={this.state.blocks[3].text} color={this.state.blocks[3].color} icon={this.state.blocks[3].icon} onClick={() => {select(3)}}/>
</View>
</Card>
{ /* This is the component that I want to hide select if the user clicked outside of this */}
<Card flat row style={styles.bottom}>
{
(option=='none')?<TableConfigs handler={this.change}/>:
(option=='color')?<ColorConfig handler={this.change} color={this.changeColor}/>:
(option=='icon')?<IconConfig handler={this.change} modal={this.setVisibility}/>:
(option=='text')?<TextConfig handler={this.change} text={this.state.selectedText} setText={this.setText}/>:
(option=='audio')?<AudioConfig handler={this.change} editting={this.state.selected} recordTime={this.state.recordTime} changeTime={this.changeTime}/>:null
}
</Card>
</View>
);
}
}
const styles = StyleSheet.create({
//Other Styles ...
full: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
width: '100%',
height: '100%',
backgroundColor: 'blue',
opacity: 0.2,
zIndex: 12,
elevation: 20,
},
});
解决方案
为什么不将叠加层放在按钮下方?这听起来更适合您的用例。这样您就可以处理按钮上的点击和按钮外部的点击(覆盖)