我有一个表格。
我尝试从不同的功能提交此表单。
为此,我创建了一个ref
。该引用在打印时具有正确的 HTML 节点,并且该节点还有一个submit
方法。当调用此提交方法时(formNode.submit()
)表单已提交,but the onSubmit
处理程序永远不会被触发。
Why?
这是一个显示相同行为的简化示例。
class Form extends React.Component {
constructor() {
super();
this.form = React.createRef();
}
render() {
return (
<div onClick={() => this.form.submit()}>
Click me!
<form
onSubmit={e => console.log(e)}
ref={f => (this.form = f)}
/>
</div>
);
}
}
https://codesandbox.io/s/vm8pkmony https://codesandbox.io/s/vm8pkmony
从 React 17 开始你必须添加cancelable
and bubbles
您的活动的属性。否则,已接受答案的解决方案将不起作用。这是由一些事件委托的变化 https://reactjs.org/blog/2020/08/10/react-v17-rc.html#changes-to-event-delegation.
this.form.dispatchEvent(
new Event("submit", { cancelable: true, bubbles: true })
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)