본문 바로가기
react

TestDome React Change Username

by 새우하이 2021. 8. 20.

문제에서 요구하는 사항을 보면

1. h1태그 사이에 value 값이 뜨게

2. 버튼을 누르면 input값을 읽어 Username 의 value를 변경

3. Reference Hook 사용해서 Username의 value update

 

// React is loaded and is available as React and ReactDOM
// imports should NOT be used
class Username extends React.Component {
  state = { value: "" };

  changeValue(value) {
    this.setState({ value });
  }

  render() {
    const { value } = this.state;
    return <h1>{value}</h1>;
  }
}

function App() {
  let ref = React.useRef('');
  function clickHandler() {
    let name = document.getElementById('input_name').value;
    ref.current.setState({value : name})
  }

  return (
    <div>
      <button onClick={clickHandler}>Change Username</button>
      <input id="input_name" type="text" />
      <Username ref={ref}/>
      
    </div>
  );
}

//아래는 생략

<sandbox code>

 

다른 부분은 건드리지 않았고 React의 Ref를 사용해서 DOM 노드에 접근했다.

functional component에서는 React.useRef()를 통해 생성되고 ref attribute를 통해 React Elements에 부착된다.

Username에 생성된 ref를 ref attribute에 부착하고 이를 clickHandler에서

1. document.getElementByID로 value값을 name이라는 변수에 담고 

2. ref.current.setState로 Username의 setState를 통해 값을 input value인 name으로 업데이트한다.

 

처음에 constructor와 super()이 없어서 추가해서 작성했다가 다시 원상태로 되돌렸는데 결론적으로 둘다 잘 된다.

https://min9nim.github.io/2018/12/super-props/

에서 class field proposal 에 대한 언급이 있는데 읽어보면 이해 된다.

https://www.testdome.com/questions/45257

 

Change Username | React | TestDome

Change Username programming interview question screens programmers for knowledge of: React.

www.testdome.com

 

'react' 카테고리의 다른 글

TestDome React Image Gallery App  (0) 2021.08.21
TestDome React Focusable Input  (0) 2021.08.20
Webpack이 뭔데!!(5)  (0) 2021.08.06
Webpack이 뭔데!! (4)  (0) 2021.08.04
Webpack이 뭔데!!(3)  (0) 2021.08.02

댓글