React函数组件如何正确将子组件输入的Age值传递给父组件
问题原因
代码里有两处直接导致异常的问题:
- 子组件年龄输入框触发
onChange时,调用父组件传入的ageToChild方法没有传任何参数,父组件拿到的入参默认就是undefined - 父组件的提交按钮
type设为了button,该类型按钮不会触发form标签绑定的handleSubmit事件,点击后不会执行打印、弹窗逻辑
修改方案
- 调整子组件
Child.js的年龄输入框事件逻辑,在回调中拿到输入事件对象,将用户输入的实际值作为参数传给ageToChild - 调整父组件
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
相关产品推荐
相关产品推荐

