FE/React & RN

[ React ] props

Chars4785 2019. 7. 17. 09:47

@ 궁금한 이유

계속하면서 어떤 경우에는 {} 를 사용하는 경우도 있고 없는 경우도 있어서 정리 하고 싶은 마음에 

 


@ 공부

import React from 'react';
function App() {
  const greeting = 'Hello Function Component!';
  return <Headline value={greeting} />;
}
function Headline(props) {
  return <h1>{props.value}</h1>;
}
export default App;
import React from 'react';
function App() {
  const greeting = 'Hello Function Component!';
  return <Headline value={greeting} />;
}
function Headline({props}) {
  return <h1>{props.value}</h1>;
}
export default App;

If you forget the JavaScript destructuring and just access props from the component's function signature like function Headline(value1, value2) { ... }, you may see a "props undefined"-messages. It doesn't work this way, because props are always accessible as first argument of the function and can be destructured from there: function Headline({ value1, value2 }) { ... }

https://www.robinwieruch.de/react-function-component

두개 이상일때는 {} 이렇게 해주는 이유가 무조건 첫번째 생성자에 접근 하기 때문에 두개 이상일 때는 {} 으로 묶어줘야 한다.

const Item = (p) =>{
  console.log(p);
  console.log({p})
  return(
    <Text>{p.props.key}</Text>
  )
}

 LOG  {"props": {"key": "Devin"}}

 LOG  {"p": {"props": {"key": "Devin"}}}

 

    <View style={{padding : 50}}>
        {data.map(t => (<Item chars={t}/>))}
    </View>

 LOG  {"chars": {"key": "Devin"}}

 LOG  {"p": {"chars": {"key": "Devin"}}}

 

결국 정리하면 부모 컴포넌트에서 던져주는 속성으로 객체를 만들어서 던져지게 되어 있다.

단 2개 이상의 속성이 던져지게 되면 또 다른 이야기가 된다.

const Item = ({chars,lee}) =>{
  console.log(chars);
  console.log(lee);
  return(
    <Text>hi</Text>
  ) 
}

function App(){
  return (
    <View style={{padding : 50}}>
        <Item chars ={data} lee ={hi} />
    </View>
  );
};

 LOG  {"key": "Devin"}

 LOG  {"name": "jong"}

import React from 'react';
import Hello from './Hello';
import './App.css';

function App() {
  const name ='react';
  const style ={
    backgroundColor: 'black',
    color: 'aqua',
    fontSize: 24,
    padding: '1rem'
  };
  return (
    <>
    {/*어쩌구*/}
      <Hello 
      // 주석 주석!!
      />
      <div>{name}</div>
      <div style={style}> 안녕하세요. </div>
      <div className="gray-box"></div>
    </>
  );
}

export default App;

 

두개 이상일때는 {} 이렇게 해주는 이유가 무조건 첫번째 생성자에 접근 하기 때문에 두개 이상일 때는 {} 으로 묶어줘야 한다.

정리하면

function Item (t) ~ 
     t.props.key
     
function Item({name,data}) ~
     name.key
      data.key

 

 


props 

> Properties 줄임말

import  React from 'react';

function Hello({color,name}){
    // return <div style={{
    //     color: props.color
    // }}>안녕!! {props.name}</div>;
    return <div style ={
        {color}
    }> 안녕하세! {name}</div>;
}

export default Hello;

 

DefaultProps

Hello.defaultProps ={
    name : '이름없음'
    
};
 return (
    <>
    <Hello name="react" color="red"/>
    <Hello color="pink"/>
    </>
  );

이렇게 되면 name 값이 없기 때문에 '이름없음' 이 된다.


Children Props

function Wrapper({children}){
 const style={
     border: '2px solid black',
     padding:16
 };

 return <div style={style}>{children}</div>
}

export default Wrapper;

이렇게 해야

function App() {
  
  return (
    <Wrapper>
    <Hello name="react" color="red"/>
    <Hello color="pink"/>
    </Wrapper>
  );
}

Hello가 Wrapper 안으로 들어가서 나오게 된다. 만약 그냥 하게 되면 Wrapper에 있는 block만 나오게 된다.


삼항연산자

function Hello({color,name,isSpecial}){
    return(
        <div style ={
            {color}
        }> 
        {isSpecial ? <b>*</b> : null }
        안녕하세요! {name}
        </div>
    );
}
<Hello name="react" color="red" isSpecial={true}
//isSpecial이라고 적어 놓으면 그냥 true 가 디폴트가 된다.
/>

이것도 가능

  return(
        <div style ={
            {color}
        }> 
        {isSpecial &&  <b>*</b> }
        안녕하세요! {name}
        </div>
    );

UseState ( react Hooks)

https://ko.reactjs.org/docs/hooks-state.html

function Counter(){
    const [number,setNer] = useState(3); //배열을 반환
    // const number = numberState[0]
    // const setNumber = numberState[1]
    // 와 같은 뜻이다.

    const onIncrease =()=>{
        setNer(prevNumber => prevNumber +1); //update 함수
        //최적화와 관련있다.
    }
    
    const onDecrease =()=>{
        setNer(number -1);
    }

    return(
        <div>
            <h1>{number}</h1>
            <button onClick={onIncrease}>+1</button>
            {/* 1. {<button onClick={onIncrease()}>+1</button>}
                onIncrease()라고 하면 안된다.
                2. 리엑트에서는 onClick 처럼 대부분 대문자 뒤에 나온
                - 원래는 onclick => onClick */}
            <button onClick={onDecrease}>-1</button>
        </div>
    )
function Counter(){
  let state ={
      count:0
  };
  
  let {name}=this.state;


  const modify = n =>{
      this.setState({
          count :n
      })
  }
  const count = this.state;
    return(
      <>
        <h1>{count}</h1>
        <button onClick={()=>{this.modify(count+1)}}></button>


      </>
    );
}

 


훅을 통한 값 리셋과 함수가 어떻게 진행되는지 보는 코드

function InputSameple(){
    const [text,setText] = useState('');
    const onChange = (e) =>{
        setText(e.target.value);
    }

    const onReset = ()=>{
        setText('');
    }

    return(
        <div>
            <input onChange={onChange} value={text} />
            <button>초기화</button>
            <div>
                <b>값: </b>
                {text}
            </div>
        </div>
    );
}

객체로 리셋

import React,{useState} from 'react';

function InputSameple(){
    const [inputs,setInputs] = useState({
        name :'',
        nickname :''
    });
    const {name, nickname} = inputs //추출하기

    const onChange = (e) =>{
        const{name,value } = e.target;
        //객체 업데이트
        setInputs({
            ...inputs,
            [name]: value,
       });
    };

    const onReset = ()=>{
        setInputs({
            name:'',
            nickname:'',
        });
    };

    return(
        <div>
            <input 
                name="name"
                placeholder="이름"
                onChange={onChange} 
                value={name}
            />
            <input 
                name="nickname" 
                placeholder="닉네임" 
                onChange={onChange} 
                value={nickname}
            />
            <button onClick={onReset}>초기화</button>
            <div>
                <b>값: </b>
                {name} ({nickname})
            </div>
        </div>
    );
}

export default InputSameple;