You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React函数组件如何正确将子组件输入的Age值传递给父组件

问题原因

代码里有两处直接导致异常的问题:

  • 子组件年龄输入框触发onChange时,调用父组件传入的ageToChild方法没有传任何参数,父组件拿到的入参默认就是undefined
  • 父组件的提交按钮type设为了button,该类型按钮不会触发form标签绑定的handleSubmit事件,点击后不会执行打印、弹窗逻辑
修改方案
  1. 调整子组件Child.js的年龄输入框事件逻辑,在回调中拿到输入事件对象,将用户输入的实际值作为参数传给ageToChild
  2. 调整父组件Parent.js的提交按钮属性,将type从button改为submit,使其可以正常触发表单提交事件

修改后完整代码

Child.js

import React from 'react'

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

export default Child

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>
            <form onSubmit={handleSubmit}>
                <label>Name : </label>
                <input type="text" value={name} onChange={(e)=>setName(e.target.value)} />
                <button type='button' onClick={()=>setToggled(!toggled)}>Age ?</button>
                {toggled && <Child childToParent={childToParent} ageToChild={ageToChild}></Child>}
                <button type='submit'>Submit</button>
            </form>
        </div>
    </>
  )
}

export default Parent
效果说明

修改完成后,点击「Age ?」按钮调出年龄输入框,输入姓名、年龄后点击提交,就能正常触发弹窗,同时控制台会正确打印两个字段的值,不会再出现Age为undefined的问题。由于年龄值存在父组件的state中,就算输入完年龄后点击按钮收起年龄输入框,已输入的年龄值也不会丢失。


内容的提问来源于stack exchange,提问作者nOhAr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 06:30:44