react-native - UseState ReactNative
问题描述
1
初学者开发者反应原生。
我正在处理设计模式问题,我在同一个组件中有多个 TouchableOpacity(我必须保持这种方式)。对于每一个我都有 onPress 功能,那就是那里的背景和反转。问题是依赖于状态当前状态的函数,当我点击其中一个时,evreyone 正在改变。
function Grocery({ navigation }) {
const [isPressed, setIsPressed] = useState(0);
const onPress = () => setIsPressed(!isPressed);
return (
<ScrollView>
<Button title="home" onPress={() => {FindMatch(GetIngridients());navigation.navigate("MatchedRecipiesScreen");}}>press</Button>
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={() => {AddToPanetry("pasta");onPress();}} >
<View style={isPressed && styles.pressedButtonStyle} />
<Image style={styles.imageright} source={require('../assets/Pastaa.jpg')} />
<Text> pasta</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {AddToPanetry("eggs");onPress();}} >
<View style={isPressed && styles.pressedButtonStyle} />
<Image style={styles.imageleft} source={require('../assets/eggs.jpg')} />
<Text>eggs</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {AddToPanetry("sugar");onPress();}} >
<View style={isPressed && styles.pressedButtonStyle} />
<Image style={styles.imageleft} source={require('../assets/sugar.jpg')} />
<Text>eggs</Text>
</TouchableOpacity>
const styles = StyleSheet.create({
container: {
flexDirection: "row",
flexWrap: "wrap",
padding: 50,
flexWrap: 'wrap',
justifyContent: 'space-between',
}
,
imageleft: {
borderRadius:100,
borderWidth:2,
borderColor:'black',
height: 120,
width: 150,
borderRadius: 80,
padding:25
},
button: {
alignItems: "center",
},
tinyLogo: {
width: 50,
height: 50,
},
pressedButtonStyle: {
position:"absolute",
width:150,
height:121,
backgroundColor:'black',
opacity:0.6,
zIndex:100,
borderRadius:80
},
imageright: {
borderRadius:100,
borderWidth:2,
borderColor:'black',
height: 120,
width: 150,
borderRadius: 80,
padding:25
}
});
有人可以告诉我在这种情况下使用带有布尔数组的 UseState 的正确方法吗?
tnx。
解决方案
您可以使用 render prop 模式仅封装给您带来麻烦的逻辑。
const ToggleWrapper = ({render, onPress}) => {
const [isPressed, setIsPressed] = useState(0);
const _onPress = () => setIsPressed(!isPressed);
return <TouchableOpacity onPress={() => {_onPress();onPress();}} >
{render(isPressed)}
</TouchableOpacity>
}
推荐阅读
- flutter - 飞镖语言问题 - 是什么意思
- java - 有人可以帮助我了解问题所在吗?它没有在 RecyclerView 中正确显示数据
- reactjs - 如何不重复相同的代码并在 react 中使用组件或函数?
- mysql - Kusto KQL equivalent to with clause
- python - 按字典列分组字典列表
- android - 我们如何计算流会话的持续时间,以及随后使用 Google Speech API 的单个应用用户的成本?
- flutter - Flutter:使构建时环境变量可用于代码
- angular - 如果改变了角度,则更新对象的字段
- php - Paypal 快速结账回调
- windows-installer - 需要在安装程序的名称中指定最新的 git 哈希