Front-end/React\RN
리엑트네이티브 프로퍼티, 컴포넌트 나누기
javapp 자바앱
2023. 5. 22. 00:00
728x90
GoalItem 부분 나누기
App.js
const addGoalHandler = () => {
setCourseGoals((currentCourseGoals) => [
...currentCourseGoals,
{
text: enteredText,
id: Math.random().toString()
},
]);
}
<FlatList
data={courseGoals}
renderItem={(itemData) => {
return <GoalItem text={itemData.item.text} />;
}}
keyExtractor={(item, index) => {
return item.id;
}}
alwaysBounceVertical={false}
/>
GoalItem.js
import { StyleSheet, View, Text } from "react-native";
function GoalItem(props) {
return (
<View style={styles.goalItems}>
<Text style={styles.goalText}>{props.text}</Text>
</View>
);
}
export default GoalItem;
const styles = StyleSheet.create({
goalItems: {
margin: 8,
padding: 8,
borderRadius: 6,
backgroundColor: "#5e0acc",
},
goalText: {
color: "white",
},
});
입력부분 나누기
GoalInput.js
import { useState } from "react";
import { View, TextInput, Button, StyleSheet } from "react-native";
function GoalInput(props) {
const [enteredText, setEnteredText] = useState("");
const goalInputHandler = (enteredText) => {
setEnteredText(enteredText);
};
const addGoalHandler = () => {
if (enteredText === '') {
return;
}
props.onAddGoal(enteredText);
setEnteredText("");
};
return (
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
placeholder="Your Course 목표!"
onChangeText={goalInputHandler}
value={enteredText}
/>
<Button title="목표 추가" onPress={addGoalHandler} />
</View>
);
}
export default GoalInput;
const styles = StyleSheet.create({
inputContainer: {
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 24,
borderBottomWidth: 1,
borderBottomColor: "#cccccc",
},
textInput: {
borderWidth: 1,
borderColor: "#cccccc",
width: "70%",
marginRight: 8,
padding: 8,
},
});
onAddGoal은 addGoalHandler메소드를 가리키고 있고 해당 메소드는 파라미터 1개가 필요하다.
onPress를 통해 addGoalHandler메소드가 실행되고, props.onAddGoal(enteredText); 호출
App.js
export default function App() {
const [courseGoals, setCourseGoals] = useState([])
const addGoalHandler = (enteredText) => {
setCourseGoals((currentCourseGoals) => [
...currentCourseGoals,
{
text: enteredText,
id: Math.random().toString(),
},
]);
};
return (
<View style={styles.appContainer}>
<GoalInput onAddGoal={addGoalHandler}/>
GoalInput.js 에서 props 로 onAddGoal을 호출하여 addGoalHandler를 실행