ref
#React
https://reactjs.org/docs/refs-and-the-dom.html
なにこれ
ref は、props 以外で子コンポーネントとインタラクションできる方法。
DOMノード or コンポーネントへの参照を取得できるよ
どうする
1. まず参照をつくる
code:ts
class Sample extends React.Component {
constructor(props: any) {
super(props);
// refを作るゾ
this.myRef = React.createRef();
}
}
2. DOM(もしくはコンポーネント)に参照指定させる
code:ts
class Sample extends React.Component {
render () {
return (
<input type="text" ref={this.myRef} onChange={this.onChange} />
)
}
}
3. つかう
code:ts
class Sample extends React.Component {
private const onChange = () => {
// なんとrefで指定したDOMにアクセスできる
this.myRef.current.focus();
}
}
参考: https://medium.com/@sgroff04/introduction-to-refs-in-react-16-3-d94505b45a73
Hooks
いまはこっち。
React.useRef
あとrefにはuseRef or createRef した以外のモノも入れられる