简体   繁体   中英

How do I get the Age data from child to parent component

Parent.js

import React, { useState } from 'react'
import Child from './Child'

const Parent = () => {
    const[data,setData] = useState('')
    const[name,setName] = useState('')
    const[toggled,setToggled] = useState(false)
    const[age,setAge] = useState('')

    const ageToChild = (ageData) =>{
        setAge(ageData)
    }
    const childToParent = (childData) =>{
        setData(childData)
    }

    const handleSubmit = (e) =>{
        e.preventDefault()
        alert(`Age is ${age} , Form Submitted`)
        console.log(`Name is ${name} and Age is ${age}`)
    }
  return (
    <>
        {data}
        <div>
            {/* <Child childToParent={childToParent}></Child> */}
            <form onSubmit={handleSubmit}>
                <label>Name : </label>
                <input type="text" value={name} onChange={(e)=>setName(e.target.value)}></input>
                <button type='button' onClick={()=>setToggled(!toggled)}>Age ?</button>
                {toggled && <Child childToParent={childToParent} ageToChild={ageToChild}></Child>}
                <button type='button'>Submit</button>
            </form>
        </div>
    </>
  )
}

export default Parent

Child.js

import React from 'react'

const Child = ({childToParent,ageToChild}) => {
    const data = "This is some data from the child component to parent"
    // const age = ageToChild
  return (
    <>
        <button onClick={()=>childToParent(data)}>Click Child</button>
        <label>Age : </label>
        <input type='text' onChange={()=>ageToChild()}></input>
    </>
  )
}

export default Child

I am getting output as Name is inputtedname and Age is Undefined , How do I get the user inputted age value logged in the console? I am trying to pass data from child to parent using functional components

使用此代码:

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

如果你想将年龄值从 Child.js 组件传递给 alert() ,你应该将e.target.value添加到onChange

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

Make sure to pass the ageToChild function from the parent component to the child:

<Child childToParent={childToParent} ageToChild={ageToChild} />

Then from the Child component you can simply do:

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

You have forgotten to pass the value in the function😁. Try passing it in onChange .

onChange={(e)=>ageToChild(e.target.value)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM