ReactJSでcontrolled componentsとuncontrolled components
ReactJSで入力フィールドの値を取得する方法
ref
を使用して、入力フィールドのDOM要素への参照を取得できます。その後、ref.current.value
を使用して、その要素の値を取得できます。
const MyComponent = () => {
const inputRef = useRef();
const handleClick = () => {
const value = inputRef.current.value;
console.log(value); // 入力された値が出力されます
};
return (
<div>
<input ref={inputRef} />
<button onClick={handleClick}>送信</button>
</div>
);
};
useState
を使用して、入力フィールドの値を状態変数に格納できます。その後、useState
フックの2番目の要素を使用して、その値を取得できます。
const MyComponent = () => {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<div>
<input value={value} onChange={handleChange} />
</div>
);
};
defaultValue
を使用して、入力フィールドの初期値を設定できます。その後、value
プロパティを使用して、その値を取得できます。
const MyComponent = () => {
return (
<div>
<input defaultValue="初期値" />
</div>
);
};
controlled componentsとuncontrolled components
上記の例はすべて、controlled components
と呼ばれるパターンを使用しています。controlled components
では、Reactコンポーネントが常にフィールドの値を制御します。
一方、uncontrolled components
では、DOM要素自身が値を制御します。uncontrolled components
を使用するには、ref
を使用してDOM要素への参照を取得し、ref.current.value
を使用して値を取得する必要があります。
どの方法を使うべきかは、状況によって異なります。一般的には、useState
を使うのが最も簡単で効率的な方法です。ただし、複数のコンポーネント間で値を共有する必要がある場合は、ref
を使う必要があるかもしれません。
const MyComponent = () => {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<div>
<input value={value} onChange={handleChange} />
<p>入力された値: {value}</p>
</div>
);
};
このコードを実行すると、以下のような画面が表示されます。
ユーザーが入力フィールドに入力すると、handleChange
関数が呼び出され、入力された値がvalue
変数に格納されます。その後、value
変数の値がp
要素に表示されます。
このサンプルコードは、useState
を使用して入力フィールドの値を取得する方法を理解するための簡単な例です。この方法を応用することで、さまざまな入力フィールドの値を取得することができます。
入力フィールドの値を取得するその他の方法
onInput
イベントを使用して、ユーザーが入力するたびに値を取得できます。
const MyComponent = () => {
const handleChange = (event) => {
console.log(event.target.value); // 入力された値が出力されます
};
return (
<div>
<input onInput={handleChange} />
</div>
);
};
onChange
イベントを使用して、値が変更されたときに値を取得できます。
const MyComponent = () => {
const handleChange = (event) => {
console.log(event.target.value); // 入力された値が出力されます
};
return (
<div>
<input onChange={handleChange} />
</div>
);
};
Formikなどのライブラリを使用して、入力フィールドの値を簡単に取得できます。
import Formik from 'formik';
const MyComponent = () => {
return (
<Formik
initialValues={{
name: '',
email: '',
}}
onSubmit={(values) => {
console.log(values); // 入力された値が出力されます
}}
>
{(formik) => {
return (
<form onSubmit={formik.handleSubmit}>
<input name="name" onChange={formik.handleChange} />
<input name="email" onChange={formik.handleChange} />
<button type="submit">送信</button>
</form>
);
}}
</Formik>
);
};
javascript reactjs