我有三个按钮,名为药丸,糖浆和注射器。用户必须从这3个按钮中选择一个按钮。如果用户选择糖浆,则注射器和药丸都必须返回假。这类似于切换按钮的概念。请分享您的想法或任何链接,以供参考。
下面是我的文件单键按钮。
Priscription.js
<SelectDeselectButton
iconName={'briefcase-medical'}
iconFamily={"FontAwesome5"}
iconBgColor={COLOR_WHITE}
iconColor={COLOR_BLACK}
selectedColor={COLOR_ORANGE}
iconSize={30}
initialSelection={isButtonSelected}
onClickEvent={(item) => setIsButtonSelected(item)}
/>ToggleButton.js
import React, { useState } from 'react';
import { StyleSheet } from 'react-native'
import { View, Button, Icon } from "native-base";
//RESPONSIVE
import { useScreenDimensions } from '../../ORIENTATION/useOrientation'
import { normalize } from '../../ORIENTATION/FontScale'
import { COLOR_WHITE } from '../Constants/Colors'
const SelectDeselectButton = ({iconName, iconBgColor, iconColor, iconFamily, iconSize,
selectedColor, onClickEvent, initialSelection}) =>
{
const screenData = useScreenDimensions();
const screenWidth = screenData.width;
const screenHeight = screenData.height;
const [isSelected, setIsSelected] = useState(initialSelection);
const styles = StyleSheet.create({
button:
{
width: screenWidth > screenHeight ? screenHeight / 4.5 : screenWidth / 3.5,
height: screenWidth > screenHeight ? '50%' : '42%',
backgroundColor: isSelected ? selectedColor : iconBgColor,
shadowOpacity: 0.25,
shadowRadius: 5,
shadowColor: 'gray',
shadowOffset: { height: 0, width: 0 },
elevation: 1,
justifyContent:'center',
alignItems:'center'
},
icon:
{
fontSize:screenWidth > screenHeight ? normalize(iconSize) : normalize(iconSize+8),
color: isSelected ? COLOR_WHITE : iconColor,
}
})
const buttonHandler = () =>
{
setIsSelected(!isSelected);
if(onClickEvent !== null)
onClickEvent(isSelected);
}
return(
<View>
<Button rounded style={styles.button} onPress={() => buttonHandler()}>
<Icon name={iconName} style={styles.icon} type={iconFamily}/>
</Button>
</View>
)
}
export default SelectDeselectButton;提前谢谢。
发布于 2020-11-25 13:09:41
set不是以isSelected作为布尔值,而是将按钮名作为字符串。然后,您只需要比较按钮名称,以检查它是否被选中。
Toggle Button.js // I为简单起见更改了组件
const toggleButton = (type) => {
const buttonHandler = () =>
{
setIsSelected(type);
if(onClickEvent !== null)
onClickEvent(isSelected);
}
return(
<View>
<Button rounded style={isSelected === type ? styles.activeButton : styles.button} onPress={() => buttonHandler()}>
<Icon name={iconName} style={styles.icon} type={iconFamily}/>
</Button>
</View>
)
}
}Prescription.js
import ToggleButton from './ToggleButton'
...
const [isSelected, setIsSelected] = useState('');
<ToggleButton type = 'Syringe' isSelected = {isSelected} setIsSelected={setIsSelected}/>
<ToggleButton type = 'Pill' isSelected = {isSelected} setIsSelected={setIsSelected}/>
<ToggleButton type = 'Syrup' isSelected = {isSelected} setIsSelected={setIsSelected}/>我传递isSelected和处理程序的原因是要控制父组件中的状态,以便所有按钮都使用相同的状态。
https://stackoverflow.com/questions/65005149
复制相似问题