添加 onChange 反应打字稿后无法在文本字段中输入
我正在尝试将 onChange 事件添加到我的输入字段组件,但是当我使用 onChange 事件处理程序时,我无法再在输入组件中键入内容 这是我的输入 props 接口
export interface InputFieldProps {
className?: string;
label?: string;
InputType?: 'email' | 'password' | 'search';
placeholder?: string;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
}
,这是我的组件调用
<InputField
label="Email"
InputType="email"
className="firstInput"
placeholder="Email"
onChange={(e) => {
setEmail(e.target.value);
}}
/>
,这是我在组件中添加 prop onChange 的位置(无法添加代码,因为它太长)
I'm trying to add a onChange event to my input field component but when I the onChange evenet handler I can no longer type in my input component
this is my input props interface
export interface InputFieldProps {
className?: string;
label?: string;
InputType?: 'email' | 'password' | 'search';
placeholder?: string;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
}
and this is my component call
<InputField
label="Email"
InputType="email"
className="firstInput"
placeholder="Email"
onChange={(e) => {
setEmail(e.target.value);
}}
/>
and this is where I'm adding the prop onChange in my component (couldn't add code because it's too long)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将 value 属性添加到您的 InputField 中,以便它实际显示该值。您正在更新电子邮件状态,但没有告诉 InputField 显示电子邮件状态。
应该做到这一点。然后您需要做的就是确保在您的文件中添加 value={value} 并确保该 prop 与您解压 onChange 的位置相同。
我会给你一个片段,但你已经包含了这个的屏幕截图,而不是实际的代码块。
更新
从样式组件中删除逻辑(从InputField函数中删除onChange和值)似乎已经在你的小提琴中为我解决了这个问题。
我必须承认,虽然我对 mui v4 有很多经验,但我还没有阅读过 mui v5 中样式组件的新方法。但是,我猜想将逻辑(状态和状态更改)混合到样式组件中是不明智的。看来最好将其分开。
请参阅我在此处所做的更改:https://codesandbox。 io/s/xenodochial-northcutt-mkbbye?file=/src/InputField.tsx
You need to add the value prop to your InputField so that it actually displays that value. You are updating the email state, but not telling the InputField to display the email state.
Should do the trick. Then all you need to do is make sure that in your you add value={value} and make sure the prop is unpacked the same place you unpack onChange.
I would give you a snippet but you have included a screenshot for this and not an actual code block.
UPDATE
Removing the logic from the styled component (removing onChange and value from the InputField function) seems to have resolved this issue for me in your fiddle.
I have to admit though I have a lot of experience with mui v4 I haven't read up on the new way of styling components in mui v5. However, I would guess that it is unwise to mix logic (state and state change) into the styled component. It seems like it is best to keep that separate.
See the changes I made here: https://codesandbox.io/s/xenodochial-northcutt-mkbbye?file=/src/InputField.tsx