React中<form>标签action传函数报错,按官方文档编写却无法运行求助
React 18.3.1 表单提交警告与弹窗未触发问题解决
你使用React 18.3.1编写的Search组件出现了action属性无效的警告,同时提交时alert弹窗未触发,核心原因是你参考的官方文档特性属于React 19,而React 18并不支持将函数作为<form>的action属性值。
你的代码:
// handle form submitting from client side export default function Search() { function search(formData) { const query = formData.get("query"); alert(`You searched for '${query}'`); } return ( <form action={search}> <input name="query" /> <button type="submit">Search</button> </form> ); }
控制台警告:
react-dom.development.js:86 Warning: Invalid value for prop action on form tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior at form at Search printWarning @ react-dom.development.js:86 error @ react-dom.development.js:60 warnUnknownProperties @ react-dom.development.js:3815 validateProperties$2 @ react-dom.development.js:3827 validatePropertiesInDevelopment @ react-dom.development.js:9541 setInitialProperties @ react-dom.development.js:9830 finalizeInitialChildren @ react-dom.development.js:10950 completeWork @ react-dom.development.js:22193 completeUnitOfWork @ react-dom.development.js:26596 performUnitOfWork @ react-dom.development.js:26568 workLoopSync @ react-dom.development.js:26466 renderRootSync @ react-dom.development.js:26434 performConcurrentWorkOnRoot @ react-dom.development.js:25738 workLoop @ scheduler.development.js:266 flushWork @ scheduler.development.js:239 performWorkUntilDeadline @ scheduler.development.js:533 Show 16 more frames Show less
解决方法
方法1:升级到React 19
如果你的项目允许升级版本,直接升级React和React-DOM到19版本后,你的现有代码即可正常运行,无需修改——因为将函数作为form的action属性是React 19新增的客户端表单提交处理特性。
方法2:使用React 18兼容的传统处理方式
保持React 18.3.1版本不变,改用onSubmit事件处理表单提交,并手动阻止默认行为:
export default function Search() { function handleSubmit(e) { // 阻止浏览器默认的表单提交行为 e.preventDefault(); // 从表单元素获取FormData const formData = new FormData(e.target); const query = formData.get("query"); alert(`You searched for '${query}'`); } return ( <form onSubmit={handleSubmit}> <input name="query" /> <button type="submit">Search</button> </form> ); }
这段代码通过onSubmit绑定处理函数,先调用e.preventDefault()避免页面刷新,再通过FormData获取表单输入值,既消除了警告,也能正常触发alert弹窗。
内容的提问来源于stack exchange,提问作者Mohan mohan
相关产品推荐
相关产品推荐

