react.js 기본 (노마드 강의) - props

mini·2022년 10월 17일
0

개요: 같은 ui를 반복적으로 사용해야 할때 중복 styled을 쓴다라고 가정했을 때 코드를 재 사용하기 위해..(바깥에서 내용을 함수로 전달.,.,?)
리액트js는 자동으로 속성처럼 넣은 모든 property(prop)들을 오브젝트로 넣어주고 컴포넌트의 첫번째 인자로 넣어준다. props는 두번쨰 인자는 없다. 첫번째 인자에 모두 오브젝트로 넣어준다.

예시)


  function Btn({banana, big}) { // -> shortcut : (props)
    // console.log(props) //첫번째 인자는 컴포넌트 속성의 첫번째 값을 가져온다.
    return <button
      style={{
        backgroundColor: "tomato",
        color: "white",
        padding: "10px 20px",
        border: 0,
        borderRadius: 10,
        fontSize: big ? 18 : 16,
      }}>
        {banana} 
        {/* -> shortcut : {props.banana} */}
      </button>
  }

  function App() {
    return (
    <div className="flex-direction: column">
      <Btn banana="Save Change" big={false}/>
      <Btn banana="바뀌니" big={true}/>
    </div>
    )
  }
  • 추가 Prop Types
  function Btn({text, changeValue, fontSize}) {
    console.log(text, "was changed")
    return <button
      onClick={changeValue}
      style={{
        fontSize: fontSize,
      }}>
        {text}
      </button>
  }
  
  function App() {
    const [value, setValue] = React.useState("Save Changes");
    const changeValue = () => setValue("Revert Changes");

    return (
    <div className="flex-direction: column">
      <MemorizedBtn text={value} changeValue={changeValue}/>
      <MemorizedBtn text="Continue" fontSize="20"/>
    </div>
    )
  }

해당 예시를 보면 부모에서 fontsize value는 '20' 텍스트가 아니라 {20} 숫자로 전달 하여야 하는데 잘못 전달 하고 있다. 하지만 리액트는 코드상 아무런 에러가 없기 때문에 에러를 반환 하지 않는다. 그래서 import PropTypes from 'prop-types'; 을 이용 하면 에러를 반환 할 수 가 있다.

예시)


  function Btn({text, changeValue, fontSize}) {
    console.log(text, "was changed")
    return <button
      onClick={changeValue}
      style={{
        fontSize: fontSize,
      }}>
        {text}  {/* -> shortcut : {props.banana} */}
      </button>
  }

  const MemorizedBtn = React.memo(Btn);

  Btn.propTypes ={
    text: PropTypes.string,
    fontSize: PropTypes.number
  }

  function App() {
    const [value, setValue] = React.useState("Save Changes");
    const changeValue = () => setValue("Revert Changes");

    return (
    <div className="flex-direction: column">
      <MemorizedBtn text={value} changeValue={changeValue}/>
      <MemorizedBtn text="Continue" fontSize="20"/>
    </div>
    )
  }

Warning: Failed prop type: Invalid prop fontSize of type string supplied to Btn, expected number.

이제 상단의 에러를 반환해서 어떤 prop에 어떤 데이터를 넣어야 할지 알수가 있다.
해당 옵션에는 string, number, bool, func, object, sybol, / element, node 도 테스트 할수잇다. 이 문자인지 저 문자인지 상세히 정할수있다. required 도 설정 할수있다.

Btn.propTypes ={
    text: PropTypes.string,
    fontSize: PropTypes.number.isRequired
  }

자바스크립트로 인한 기본값 설정도 할수 있다.


  function Btn({text, changeValue, fontSize = 12}) { // fontSize = 14 -> 기본 value
    return <button
      onClick={changeValue}
      style={{
        fontSize: fontSize,
      }}>
        {text}  {/* -> shortcut : {props.banana} */}
      </button>
  }

  const MemorizedBtn = React.memo(Btn);

  Btn.propTypes ={
    text: PropTypes.string.isRequired,
    fontSize: PropTypes.number
  }

  function App() {
    const [value, setValue] = React.useState("Save Changes");
    const changeValue = () => setValue("Revert Changes");

    return (
    <div className="flex-direction: column">
      <MemorizedBtn text={value} changeValue={changeValue}/>
      <MemorizedBtn text="Continue" fontSize={20}/>
    </div>
    )
  }

0개의 댓글