가티있는블로그

[react native] 함수선언, 배열

2019. 11. 12. 22:26 | 프로그래밍/react native

  //처음엔 비어있으니까 ''로 비워둠.
  const [enterGoal, setEnteredGoal] = useState('');

 

 

먼저 변수를 선언해 줍니다.

 

  function goalInputHandler(enteredText) {
    //enteredText는 string
    setEnteredGoal(enteredText);
  }

  const goalInputHandler = enteredText => {
    setEnteredGoal(enteredText);
  };

메소드를 선언하는 방법에는 위와 같이 두가지 방법이 있습니다. 위 코드는 같은 역할을 하는 메소드를 다르게 표현한것입니다.

물론 인라인으로도 사용이 가능하지만 코드가 복잡해지기 때문에 이렇게 따로 선언해서 사용해주는게 편합니다.

 

  return (
    <View style={styles.screen}>
      <View style={styles.inputContainer}>
        <TextInput
          placeholder="Add your Bucket list"
          style={styles.input}
          onChangeText={goalInputHandler}
          value={enterGoal}
        />
        <Button title="ADD" onPress={addGoalHandler} />
      </View>
      <View> </View>
    </View>
  );

코드내에서 사용하는 방법입니다.

TextInput에서 text에 입력된 값을 enterGoal값으로 설정합니다.

Button에서 onPress즉 버튼을 눌렀을때 해당 메소드를 즉 addGoalHandler을 동작하도록합니다.

 


 

이제 값을 저장하기 위한 배열값을 생성해보겠습니다.

const [couseGoals, setCoursgoals] = useState([]);

  const addGoalHandler = () => {
    //새로운 array를 만드는데 좌측은 원래 있었던값 전부이고, 우측은 새로 추가할 값
    setCoursgoals([...couseGoals, enterGoal]);
    //다른문법사용. 이게더낫다
    setCoursgoals(currentGoals => [...couseGoals, enterGoal]);
  };

addGoalHandler은 배열에 TextInput에 입력한 값을 추가하는 메소드입니다.

setCoursgoals을 위의 코드에선 두가지 방법으로 나타냈다.

 

      <View>
        {couseGoals.map((goal) => <Text>{goal}</Text>)}
      </View>

 

java script의 map method를 사용 기존 자바스크립트 코드와 동일한 역할. 배열의 모든 요소에 접근함.

해당 코드는 courseGoals의 요소 한개인 goal을 Text로 출력해준다. 즉 모든요소를 Text로 출력해주는거.

 

이때 Text에 key값을 넣어서 요소를 구별할 수 있도록 하라는 warning이 뜬다. 

      <View>
        {couseGoals.map((goal) => <Text key={goal}>{goal}</Text>)}
      </View>

위 코드는 goal값을 key로 쓰는데 key는 unique한 값이여야한다. 그래서 만약 같은 goal을 입력하게되면 문제가 생기게된다.

 

Text에 style을 입힐때 Text는 View보다 적은 스타일을 지원하기때문에 Text를 View로 rapping해준다.

'프로그래밍 > react native' 카테고리의 다른 글

[React Native] Style  (0) 2019.11.10
[Visual Studio Code] code formatting 줄정리  (0) 2019.11.03
[React Native] layout  (0) 2019.11.03
[React Native] Button(using Hook), View  (0) 2019.10.28
[React Native] What is react native  (0) 2019.10.27