반응형
React Native에서 누를 때 버튼 스타일 변경
눌렀을 때 앱의 버튼 스타일을 바꾸고 싶습니다.어떻게 하면 좋을까요?
사용하다TouchableHighlight
.
다음은 예를 제시하겠습니다.
import React from 'react';
import { TouchableHighlight, View, Text, StyleSheet } from 'react-native';
export default function Button() {
var [ isPress, setIsPress ] = React.useState(false);
var touchProps = {
activeOpacity: 1,
underlayColor: 'blue', // <-- "backgroundColor" will be always overwritten by "underlayColor"
style: isPress ? styles.btnPress : styles.btnNormal, // <-- but you can still apply other style changes
onHideUnderlay: () => setIsPress(false),
onShowUnderlay: () => setIsPress(true),
onPress: () => console.log('HELLO'), // <-- "onPress" is apparently required
};
return (
<View style={styles.container}>
<TouchableHighlight {...touchProps}>
<Text>Click here</Text>
</TouchableHighlight>
</View>
);
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
btnNormal: {
borderColor: 'blue',
borderWidth: 1,
borderRadius: 10,
height: 30,
width: 100,
},
btnPress: {
borderColor: 'blue',
borderWidth: 1,
height: 30,
width: 100,
}
});
React Native는 새로운 기능을 제공합니다.Pressable
여러 단계의 프레스 상호 작용을 감지할 수 있는 구성 요소입니다.따라서 컴포넌트의 색상(일반적으로 임의의 스타일)을 변경하려면 다음 예를 참조하십시오.
<Pressable
style={({ pressed }) => [{ backgroundColor: pressed ? 'black' : 'white' }, styles.btn ]}>
{({ pressed }) => (
<Text style={[{ color: pressed ? 'white' : 'black' }, styles.btnText]}>
{text}
</Text>
)}
</Pressable>
코드 분석:
style={({ pressed }) => [{ backgroundColor: pressed ? 'black' : 'white' }, styles.btn ]}
여기서 스타일 소품은 프레스를 받는다(부울런).Pressable
를 누르거나 누르지 않고 스타일 배열을 반환합니다.
{({ pressed }) => (
<Text style={[{ color: pressed ? 'white' : 'black' }, styles.btnText]}>
{text}
</Text>
)}
여기서 텍스트 스타일도 다음과 같이 수정할 수 있습니다.pressed
어린이도 이용할 수 있습니다.Pressable
요소.
소품 사용:
underlayColor
<TouchableHighlight style={styles.btn} underlayColor={'gray'} />
https://native.dev/touchable 하이라이트
ES6에서 Besart Hoxhaj의 답변입니다.이 질문에 대답하면 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
}
});
다음과 같은 것을 사용합니다.
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를 사용하는 경우 style 속성 대신 className을 사용할 수 있습니다.
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를 어떻게 적용하는지는 중요하지 않습니다."handler Button On Click" 메서드에 주목하십시오.
상태가 변경되면 컴포넌트가 재렌더됩니다("렌더" 메서드가 다시 호출됩니다).
행운을 빈다;)
언급URL : https://stackoverflow.com/questions/34625829/change-button-style-on-press-in-react-native
반응형
'sourcecode' 카테고리의 다른 글
Python에서 JSON 출력 색칠하기 (0) | 2023.02.23 |
---|---|
ASP를 정지하는 방법JQuery를 사용하기 위해 ID를 변경하는 NET (0) | 2023.02.23 |
jquery를 사용하여 단추를 동적으로 추가하는 방법 (0) | 2023.02.23 |
PDF Blob - 팝업창에 콘텐츠가 표시되지 않음 (0) | 2023.02.23 |
Springfox swagger-ui.html이 기본 URL을 추론할 수 없음 - 쿠키 누락으로 인해 발생함 (0) | 2023.02.23 |