Often times in pure javascript + html + css, you would do something like:
document.querySelector('input').focus()
And the purpose of this is to get the reference of <input> tag, then call a method on it.
However, in react, you can do it in a much more convenient way by:
- saving the reference of a tag to a state of that class
- using that reference.
class SomeComponent extends React.Component{
...
hello; //declare a state where the reference of the tag can be stored
someFunction = (e)=>{
e.preventDefault();
hello.focus();
}
render(){
return (<div>
<input ref={(e)=>this.hello=e} type="text" />
<button onClick={this.someFunction}> click me to focus! </button>
</div>);
}
}
'Archive until 15 Jul 2021 > Learning React' 카테고리의 다른 글
UseContext (0) | 2021.01.07 |
---|---|
React - switching from class way to functional way (ft. hooks) (0) | 2021.01.02 |
React - times table (0) | 2021.01.02 |
React - Babel and JSX (0) | 2021.01.02 |
How react integrates with html code (0) | 2021.01.02 |