Я хочу, чтобы стиль кнопки в моем приложении менялся при нажатии. Каков наилучший способ сделать это?
Сменить стиль кнопки при нажатии кнопки React Native
Ответ 1
Используйте TouchableHighlight
.
Вот пример:
'use strict';
import React, {
Component,
StyleSheet,
PropTypes,
View,
Text,
TouchableHighlight
} from "react-native";
export default class Home extends Component {
constructor(props) {
super(props);
this.state = { pressStatus: false };
}
_onHideUnderlay() {
this.setState({ pressStatus: false });
}
_onShowUnderlay() {
this.setState({ pressStatus: true });
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight
activeOpacity={1}
style={
this.state.pressStatus
? styles.buttonPress
: styles.button
}
onHideUnderlay={this._onHideUnderlay.bind(this)}
onShowUnderlay={this._onShowUnderlay.bind(this)}
>
<Text
style={
this.state.pressStatus
? styles.welcomePress
: styles.welcome
}
>
{this.props.text}
</Text>
</TouchableHighlight>
</View>
);
}
}
Home.propTypes = {
text: PropTypes.string.isRequired
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
},
welcome: {
fontSize: 20,
textAlign: "center",
margin: 10,
color: "#000066"
},
welcomePress: {
fontSize: 20,
textAlign: "center",
margin: 10,
color: "#ffffff"
},
button: {
borderColor: "#000066",
borderWidth: 1,
borderRadius: 10
},
buttonPress: {
borderColor: "#000066",
backgroundColor: "#000066",
borderWidth: 1,
borderRadius: 10
}
});
Ответ 2
Используйте опору:
underlayColor
<TouchableHighlight style={styles.btn} underlayColor={'gray'} />
https://facebook.github.io/react-native/docs/touchablehighlight.html
Ответ 3
используйте что-то вроде этого:
class A extends React.Component {
constructor(props){
super(props);
this.state = {
onClicked: false
}
this.handlerButtonOnClick = this.handlerButtonOnClick.bind(this);
}
handlerButtonOnClick(){
this.setState({
onClicked: true
});
}
render() {
var _style;
if (this.state.onClicked){ // clicked button style
_style = {
color: "red"
}
}
else{ // default button style
_style = {
color: "blue"
}
}
return (
<div>
<button
onClick={this.handlerButtonOnClick}
style={_style}>Press me !</button>
</div>
);
}
}
Если вы используете внешний CSS, вы можете использовать className вместо свойства style:
render() {
var _class = "button";
var _class.concat(this.state.onClicked ? "-pressed" : "-normal") ;
return (
<div>
<button
onClick={this.handlerButtonOnClick}
className={_class}>Press me !</button>
</div>
);
}
Неважно, как вы применяете свой CSS. Следите за методом "handlerButtonOnClick".
Когда состояние изменяется, компонент повторно отображается (метод "render" вызывается снова).
Удачи;)
Ответ 4
Это ответ Besart Hoxhaj в ES6. Когда я отвечаю на это, React Native равен 0,34.
import React from "react";
import { TouchableHighlight, Text, Alert, StyleSheet } from "react-native";
export default class TouchableButton extends React.Component {
constructor(props) {
super(props);
this.state = {
pressed: false
};
}
render() {
return (
<TouchableHighlight
onPress={() => {
// Alert.alert(
// 'You clicked this button',
// 'Hello World!',
// [
// {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
// {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
// {text: 'OK', onPress: () => console.log('OK Pressed')},
// ]
// )
}}
style={[
styles.button,
this.state.pressed ? { backgroundColor: "green" } : {}
]}
onHideUnderlay={() => {
this.setState({ pressed: false });
}}
onShowUnderlay={() => {
this.setState({ pressed: true });
}}
>
<Text>Button</Text>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
button: {
padding: 10,
borderColor: "blue",
borderWidth: 1,
borderRadius: 5
}
});
Ответ 5
Самый простой способ с TouchableOpacity:
<TouchableOpacity
style={ this.state.active? styles.btnActive : styles.btn}
onPress={() => this.setState({active: !this.state.active})}>
</TouchableOpacity>