英文:
change background color on click react native
问题
我想让我的按钮从白色更新背景颜色到蓝色,再次单击时,我希望将背景颜色设置为白色。如何从样式表中实现这个目标?如果不行,我应该如何做?
按钮:
<TouchableOpacity style={styles.circular}></TouchableOpacity>
样式:
circular: {
width: 15,
height: 15,
borderColor: '#55bcf6',
borderRadius: 5,
borderWidth: 3,
backgroundColor: 'white'
}
英文:
i want to make my button update its background color from white to blue and when i click again i want to make the background white again. how can is it possible to do this from the stylesheet? if not how can i do this
button:
<TouchableOpacity style = {styles.circular}></TouchableOpacity>
style:
circular:{
width:15,
height:15,
borderColor:'#55bcf6',
borderRadius:5,
borderWidth:3,
backgroundColor:'white'
},
答案1
得分: 1
尝试添加一个 onClick 属性、一个颜色状态和一个动态样式,类似于以下方式:
const [color, setColor] = useState("white");
<TouchableOpacity
onPress={() => setColor(color === 'blue' ? 'white' : 'blue')}
style={{backgroundColor: color}}
>
</TouchableOpacity>
英文:
Try adding an onClick attribute, a color state and a dynamic style, something like this:
const [color, setColor] = useState("white");
<TouchableOpacity
onPress={() => setColor(color === 'blue' ? 'white' : 'blue')}
style={{backgroundColor: color}}
>
</TouchableOpacity>
答案2
得分: 1
翻译结果如下:
使用[]的样式
const [color, setColor] = useState("white");
<TouchableOpacity
onPress={() => setColor(color==='blue' ? 'white' : 'blue')}
style={[styles.circular, {backgroundColor: color}]}
>
</TouchableOpacity>
英文:
using [] in style
const [color, setColor] = useState("white");
<TouchableOpacity
onPress={() => setColor(color==='blue' ? 'white' : 'blue')}
style={[styles. circular, {backgroundColor: color}]}
>
</TouchableOpacity>
答案3
得分: 0
你可以在那里更改背景颜色并将其应用于默认值:
const [color, setColor] = useState("white");
<TouchableOpacity
onPress={() => setColor(color === 'blue' ? 'white' : 'blue')}
style={{ ...styles.circular, backgroundColor: color }}
>
</TouchableOpacity>
英文:
there you can you change the background Color and apply it with the default
const [color, setColor] = useState("white");
<TouchableOpacity
onPress={() => setColor(color==='blue' ? 'white' : 'blue')}
style={{...styles.circular, backgroundColor: color}}
>
</TouchableOpacity>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论