본문 바로가기

Study/React

[React Native] Hook : useState

 

1. useState는 배열 괄호안에 getter와 setter 개념으로 변수를 선언하여 사용할 수 있으며, 초기값 지정이 필요하다.

 

import React, { useState } from "react";
import { Button, Text, View } from "react-native";
/* 
class App extends React.Component {

  constructor(props: any){
    super(props)

    this.state = {
      count: 0
    }    
  }
  render() {
      return (
        <View>
          <Text>You clicked { this.state.count } times</Text>  

          <Button title="Click me"
                      onPress={ ( ) => this.setState({ count: this.state.count + 1  }) } />
        </View>
      )
  }
}
export default App
 */


// function App () {
const App = () => {

  const [count, setCount] = useState( 0 )   // hook
  //       get     set                        초기값
  
  return (
    <View>
        <Text>You clicked { count } times</Text>  

        <Button title="Click me"
                    onPress={ ( ) => setCount(count + 1) } />
    </View>
  )
}

export default App

 

2. 버튼 클릭에 사용하기

 

// LikeButton.tsx

import React, { useState } from "react";
import { Button, Text, View } from "react-native";

export default function LikeButton() {

    const [liked, setLiked] = useState(false)

    function LikeBtn(){
        setLiked( !liked )
    }

    return (
        <View>
            <Text>LikeButton</Text>
            <Button title={liked ? "클릭 on" : "클릭 off" } onPress={ LikeBtn } />
        </View>
    )
}

 

import React, { useState } from "react";
import { Alert, Button, SafeAreaView, Text, ToastAndroid } from "react-native";
import LikeButton from "./src/components/LikeButton";

// 1
function btnClick(){
  console.log("btnClick 클릭!")
}

// 2
const onPress = () =>{
  //Alert.alert("home", "home 클릭되었음")
  ToastAndroid.show("home button click!", ToastAndroid.SHORT)
}

export default function App() {

  // 3
  const [liked, setLiked] = useState(false)
  const toggleLiked = () => setLiked( !liked ) 
   
  return (
    <SafeAreaView>
      <Text>Hello Tsx</Text>

      <Button title="버튼" onPress={ btnClick }></Button>

      <Button title="home" onPress={ onPress } />

      <Button title={ liked ? "click on":"click off" } onPress={ toggleLiked } />
      
      <LikeButton />

    </SafeAreaView>
  )     
}

 

3. 다른 예제 : 텍스트 인풋에 내용을 입력하면 추적하여 보이게 하기

 

import React, { useState } from "react";
import { View, Text, TextInput, Button } from "react-native";

function MyFunc(props) {
  console.log(props.name);
  props.setText("i love money");
  return <Text>{props.name}</Text>;
}

export default function App () {

  const [inputTextValue, setInputTextValue] = useState("");
  const [text, setText] = useState("");

  const handleChange = (event) => {
    const {eventCount, target, text} = event.nativeEvent;
    setInputTextValue(text);
    // console.log(eventCount);
    // console.log(target);
  }

  const handleClick = () => {
    console.log(inputTextValue);
    console.log(text);
  }


  return(
    <View>
      {/* <MyFunc name="abc" setText={setText}></MyFunc> */}
      <Text>I Love {text}</Text>
      <TextInput value={inputTextValue} onChange={handleChange} placeholder="onChange" />
      <TextInput onChangeText={(text) => setText(text)} placeholder="onChangeText" />
      <Button title="button" onPress={handleClick} />
    </View>
  )
}