简体   繁体   English

将 ReactJS 中的函数作为组件的道具传递

[英]Passing functions in ReactJS as props for components

I am a beginner to using ReactJS and I created a component like this:我是使用 ReactJS 的初学者,我创建了一个这样的组件:

function InputField(props){
    return <div>
        <label htmlFor={props.Id}>{props.label}</label>
        <input type={props.type} id={props.Id} value={props.value} 
        onChange={props.changeFunc} />
    </div>
}

After rendering the component I wasn't able to enter text inside the input box.渲染组件后,我无法在输入框中输入文本。 The state was not being updated for the hook I had created. state 没有针对我创建的钩子进行更新。

You can imagine that I have passed props to the component something like this您可以想象我已将道具传递给组件,如下所示

<InputField Id='user_email' label='Email' type='email' 
value={values.email} changeFunc={handleChange}/>

And my implementation of handleChange function还有我对handleChange function的实现

const handleChange = (event)=>{
        const {name,value} = event.target
        setValues((prevValues)=>{
            return {...prevValues,[name]:value}
        })
}

Update : Thank you everyone for pointing out that I had missed to add the name property to the input field.更新:感谢大家指出我错过了将名称属性添加到输入字段。

You are missing the name property in the input field您在输入字段中缺少名称属性

function InputField(props){
    return <div>
        <label htmlFor={props.Id}>{props.label}</label>
        <input name = {props.name} type={props.type} id={props.Id} value={props.value} 
        onChange={props.changeFunc} />
    </div>
}

<InputField Id='user_email' label='Email' type='email' 
value={values.email} changeFunc={handleChange} name="email" />

i think in handleChange event does not have name because you haven't set a name attribute for your input element我认为在handleChange事件中没有名称,因为您没有为输入元素设置名称属性

so i think you should just set name attribute:所以我认为你应该只设置名称属性:

<input
   id={props.Id}
   name="input-field-name"
   type={props.type}
   value={props.value} 
   onChange={props.changeFunc}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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