# React Ref ができること
React ref 使うタイミング
- フォーカス、テキストの選択およびメディアの再生の管理
- アニメーションの発火
- サードパーティの DOM ライブラリとの統合
# Ref 作成する
React 16.3 で導入された React.createRef()
使います。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
# Ref にアクセス
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focusTextInput();
}
render() {
return <CustomTextInput ref={this.textInput} />;
}
}
# Ref コールバック
React.createRef() で作成されたオブジェクトの ref と同様に、コンポーネント間でコールバック ref を渡すことができます。
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
render() {
return <CustomTextInput inputRef={(el) => (this.inputElement = el)} />;
}
}
# 複数ファイルをアップロード
const fileRefs = useRef<RefObject<HTMLInputElement>[]>([]);
const handleChange = (event: any, index: number) => {
if (event.target?.files[0]) {
const file = event.target.files[0];
let list = files;
list[index] = file;
setFile([...list]);
}
};
const removeFile = (index: number) => {
let list = files;
list[index] = { name: "" };
setFile([...list]);
fileRefs.current[index].current?.formTarget.valueOf();
};
{
files.map((item, i) => {
return (
<div key={i}>
<label>
<span>ファイル添付</span>
<input
type="file"
id={"attachFile" + i}
ref={(fileRefs.current[i] = createRef())}
value=""
accept=".png,.jpeg,.jpg,.JPG,.JPEG,.gif,.pdf"
onChange={(event) => handleChange(event, i)}
/>
</label>
<span>{item?.name ? item.name : "選択されていません"}</span>
<span
onClick={() => {
removeFile(i);
}}
>
削除
</span>
</div>
);
});
}
2022-11-28