React

props 와 state

인디아나쥰이 2022. 3. 24. 23:59

props란?

 

프로퍼티의 줄임말이며, 상위 컴포넌트(부모)가 하위컴포넌트(자식)에게 값을 전달할때 사용한다.

props는 읽기 전용 데이터로서 수정 할 수 없다는 특징을 가지고 있다.

 

 

컴포넌트에서의 props

//1.함수 컴포넌트에서의 props
function Welcome(props) {
	return <h1>Hello, {props.name}</h1>;
}

// 2.클래스형 컴포넌트에서의 props
class Welcome extends React.Component {
	render() {
    	return <h1>Hello, {this.props.name}</h1>;
    }
}

 

props를 이용한 컴포넌트 렌더링

...
<div id="root"></div>

function Welcome(props) {
	return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="sara" />;

ReactDOM.render(
	element, document.getElementById('root')
)

// render함수 사용법 : ReactDOM.render(element, containter[, callback])
// React 엘리먼트를 container DOM에 렌더링하고 컴포넌트에 대한 참조를 반환한다.

실행시 브라우저 화면에 Hello, Sara가 출력되는 것을 확인할 수 있다.

 

<div id="root"></div>

function Welcome(props) {
	return <h1>Hello, {props.name}</h1>;
}

function App() {
	return(
    	<div>
            <Welcome name="Sara" />
            <Welcome name="Cahal" />
            <Welcome name="Edite" />
        </div>
    )
}

ReactDOM.render(
	<App />, document.getElementById('root')
)

혹은 Welcome을 랜더링 하기 위한 App 이라는 컴포넌트를 생성하여 Welcome을 여러번 렌더링 하여 Sara, Cahal, Edite을 출력 해 줄 수도 있다.

 

State란

간단하게 생각한다면 props와 비슷한 변수 정도로 생각할수 있지만, 일반 변수와는 다르게 값이 변하면 렌더링이 일어난다는 것이 특징이다.

 

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  // componentWillUnmount() {
  //   clearInterval(this.timerID);
  // }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

 

함수형 컴포넌트의 state

function Message(props) {
  
  const [message, setMessage] = React.useState("Hello World");
   
  function saying() {
    setMessage("you again!")
  }
  
  return (
    <div>
      <h1 onClick={saying}>{message}</h1>
    </div>
  );
}

  ReactDOM.render(
    <Message/>,
    document.getElementById('root')
  );

 화면상의 Hello World를 클릭하면 you again!으로 메세지가 바뀌는 간단한 예제를 만들어보았다.

 

첫 번째 파라미터는 state(변수명)이고,

두 번째 파라미터는 state를 변경해주는 함수이다.

const [message, setMessage] = useState('초기값');

728x90
반응형