LoginSignup
4
2

More than 1 year has passed since last update.

【React】親コンポーネントのuseStateから子コンポーネントの値を管理する

Posted at

子コンポーネントからonChangeイベントを検知し、値を取得して親コンポーネントに渡します。

子コンポーネント名: Input.tsx
親コンポーネント名: Parent.tsx
この二つのコンポーネントを使用して解説を行なっていきます。

Parent.tsx

Parent.tsx
import Input from '...'

const Parent = () => {
  const [password, setPassword] = useState('')

  return <Input onChange={setPassword} />
}

Inputコンポーネントに対して、onChangeという関数をPropとして渡しています。

Input.tsx

Input.tsx
interface Props {
  onChange: (arg: string) => void
}

const Input<Props> = ({
  onChange
}) => {

  return (
    <input
      type="text"
      onChange={(e) => onChange(e.target.value)}
    />
  )
}

Parent.tsxからPropで渡ってきたonChangeイベントを受け取り、input要素で使用します。
input要素でonChangeイベントを捕捉したら、親からPropで渡ってきたonChangeを発火させます。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2