现在,当用户单击 touchableopacity 时,我已在 touchableopacity 中添加了文本,我想将该按钮的颜色从默认灰色更改为蓝色,请参见下面的屏幕截图。现在,最初 checked={this.state.newProjects}
newProjects 不存在于状态变量内,因此 onclick 它应该创建新变量,以便 checked
属性变为 true,然后颜色发生变化。所以我需要每次按下时切换按钮颜色。下面的代码不起作用。我正在尝试创建同样的东西 -> https://codesandbox.io/s/k3lzwo27z5但在 native react 中。
代码:
constructor(props) {
super(props);
this.state = {
};
}
handleClick = e => {
this.setState({
[e.target.name]: !this.state[e.target.name]
});
};
<TouchableOpacity onPress={this.handleClick('newProjects')}>
<Filterbutton name="New Projects" checked={this.state.newProjects}/>
</TouchableOpacity>
过滤按钮:
const Filterbutton = ({name, checked}) => (
<View style={checked ? styles.buttonTab : styles.defaultButtonTab}>
<Text style={styles.buttonContent}>{name}</Text>
</View>
)
export default Filterbutton;
const styles = StyleSheet.create({
defaultButtonTab: {
justifyContent: 'center',
alignItems: 'center',
maxWidth: 150,
height: 30,
padding: 10,
borderRadius: 13,
borderStyle: "solid",
borderWidth: 1.3,
borderColor: "rgba(131, 143, 158, 0.7)",
marginRight: 10,
marginTop: 10
},
buttonTab: {
justifyContent: 'center',
alignItems: 'center',
maxWidth: 150,
height: 30,
padding: 10,
borderRadius: 13,
borderStyle: "solid",
borderWidth: 1.3,
borderColor: "#1994fc",
marginRight: 10,
marginTop: 10
},
屏幕截图:
最佳答案
按钮的颜色应在 <Text>
上定义而不是
<View>
<Text style={[styles.text, checked ? styles.btnChecked : '']}>{name}</Text>
</View>
关于javascript - 如何在 React Native 中更改按钮的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54665021/