英文:
Change Style on Pressable Click React Native
问题
我正在尝试在React Native中使用Pressable创建自定义按钮,但无法在按下时更改样式。每当我按Pressable并更改样式属性时,它们会在控制台中打印出更改,但在应用程序中没有反映。
import { useState } from "react";
import { Pressable, StyleSheet, Text, View } from "react-native";
export default function Button(props) {
const [refresh, setRefresh] = useState(10);
function setBG() {
styles.container.backgroundColor = 'red';
setRefresh(1);
console.log(styles.container.backgroundColor);
console.log('called');
}
return (
<Pressable onPress={setBG}>
<View style={styles.container}>
<Text style={styles.buttonLabel}>{props.text}</Text>
</View>
</Pressable>
)
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'blue',
minWidth: 100,
minHeight: 50,
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
},
buttonLabel: {
color: 'white',
fontWeight: 700
}
})
英文:
I am trying to create a custom button using pressable in react native but I cant change the style on press. Whenever I press on the pressable and change the style properties they reflect the change when I print it in the console but it isn't reflected in the app.
import { useState } from "react";
import { Pressable, StyleSheet, Text, View } from "react-native";
export default function Button(props) {
const [refresh, setRefresh] = useState(10);
function setBG() {
styles.container.backgroundColor = 'red';
setRefresh(1);
console.log(styles.container.backgroundColor);
console.log('called');
}
return (
<Pressable onPress={setBG}>
<View style = {styles.container}>
<Text style = {styles.buttonLabel}>{props.text}</Text>
</View>
</Pressable>
)
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'blue',
minWidth: 100,
minHeight: 50,
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
},
buttonLabel: {
color: 'white',
fontWeight: 700
}
})
答案1
得分: 4
你可以传递一个样式的函数,该函数接收一个布尔值,指示当前是否被按下,并返回相应的样式。
https://reactnative.dev/docs/pressable#style
你也可以将一个渲染函数作为Pressable
的子组件传递,该函数接收一个布尔值,指示当前是否被按下,并返回相应的子元素。
https://reactnative.dev/docs/pressable#children
使用其中一个或两者都可以为按下和未按下状态呈现相应的样式。
不需要尝试自行管理状态。Pressable
会将其提供给你。
英文:
You can pass a function for style that receives a boolean indicating whether it’s currently pressed and return the appropriate styles.
https://reactnative.dev/docs/pressable#style
You can also pass a render function as a child of pressable that receives a boolean indicating whether it’s currently pressed and returns the appropriate children.
https://reactnative.dev/docs/pressable#children
Using either or both of these you can render the appropriate state for pressed and unpressed.
No need to try to manage the state yourself. Pressable will hand it to you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论