TextInput은 사용자가 텍스트를 입력할 수 있게 해주는 기본 component이다. onChangeText prop은 text가 변화할 때마다 불리는 function이고, onSubmitEditing prop은 text가 보내질 때마다 불리어 지는 function이다.
아래 예제는 single word마다 🍕로 변형해서 출력해주는 형식이다.
import React, { Component } from 'react';
import { AppRegistry, Text, TextInput, View } from 'react-native';
export default class PizzaTranslator extends Component {
constructor(props) {
super(props);
this.state = {text: ''};
}
render() {
return (
<View style={{padding: 10}}>
<TextInput
style={{height: 40}}
placeholder="Type here to translate!"
onChangeText={(text) => this.setState({text})}
/>
<Text style={{padding: 10, fontSize: 42}}>
{this.state.text.split(' ').map((word) => word && '🍕').join(' ')}
</Text>
</View>
);
}
}
// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => PizzaTranslator);
위의 예제에서, 우리는 text가 계속해서 변화하는 변수이기 때문에 state에 저장한다.
*화살표함수에서 좌측은 매개변수를 뜻함
Displaying a basic button
<Button onPress={() => { Alert.alert('You tapped the button!'); }} title="Press Me" />
버튼을 누르는 것은 "onPress" function으로 표현된다. 위의 코드에서는 alert 창이 팝업되게 구현되었다.
Button 안에서 color로 버튼의 색상을 지정할 수 있다.
Touchables
import React, { Component } from 'react';
import { Alert, AppRegistry, Button, StyleSheet, View } from 'react-native';
export default class ButtonBasics extends Component {
_onPressButton() {
Alert.alert('You tapped the button!')
}
render() {
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
<Button
onPress={this._onPressButton}
title="Press Me"
/>
</View>
<View style={styles.buttonContainer}>
<Button
onPress={this._onPressButton}
title="Press Me"
color="#841584"
/>
</View>
<View style={styles.alternativeLayoutButtonContainer}>
<Button
onPress={this._onPressButton}
title="This looks great!"
/>
<Button
onPress={this._onPressButton}
title="OK!"
color="#841584"
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
buttonContainer: {
margin: 20
},
alternativeLayoutButtonContainer: {
margin: 20,
flexDirection: 'row',
justifyContent: 'space-between'
}
});
// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => ButtonBasics);
TouchableHighlight 을 누르면 뒷배경이 어두워진다. button이나 웹상의 link에서 사용할 수 있다.
TouchableOpacity는 버튼의 투명도를 감소시킨다.
아무 반응이 없는 버튼효과를 원한다면 TouchableWithoutFeedback을 사용하면 된다.
'React Native 공부' 카테고리의 다른 글
React Native 공부 10 - 간단한 구현해보기 (0) | 2019.01.21 |
---|---|
React Native 공부 8 - Layout with Flexbox (0) | 2019.01.07 |
React Native 공부 7 - Dimensions (0) | 2019.01.07 |
React Native 공부 6 - State & Style (0) | 2019.01.07 |
React Native 공부 5 - Props (0) | 2019.01.07 |