【发布时间】:2022-01-03 08:26:18
【问题描述】:
表单组件的类型为 styled.form``,并在文件底部的组件之外定义。 问题:onSubmit 事件处理程序不起作用。官方文档在 onSubmit 上没有任何内容。
const submitHandler = e => {
e.preventDefault()
console.log(e) // nothing appears in console
}
/// ... in JSX:
<Form onSubmit={submitHandler} >
<Input placeholder="YouTube URL" required name="input" onChange={changeHandler} />
<Button type="submit" >
<Icon /> <Span>Add Song</Span>
</Button>
</Form>
//... styled form defined at the bottom of the file below export default statement:
const Form = styled.form`
display: flex;
`
我发现的解决方案是将 submitHandler 附加到表单内按钮的 onClick 事件。我不确定这一点,因为我过去从未使用过 submitHandlers 的按钮(而且我认为它甚至不能在纯 React 中使用)。
所以,这可行:
<Button type="submit" onClick={submitHandler} >Submit</Button>
【问题讨论】:
-
无法在基于您的代码片段的小型应用程序中重现 --
onSubmit工作正常。有一个完整的例子会有所帮助。 -
github.com/welschmoor/songplayer-react 是 Repo,/src/components/AddSong.js 是表单的组件。从 Button 中删除 onClick 以重现。可能是我的电脑出了问题,因为我并没有真正发现其他人有这个问题,或者是我看不到的一些错字。