You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React表单中未传递onClick给自定义Button组件,为何点击仍能提交表单?

为什么未传递onClick给Button组件却能正常触发表单提交?

我有两个组件:CourseInput.js和Button.js。在CourseInput组件的表单中使用Button组件时,仅传递了type作为props,但Button组件里并未接收onClick函数,却能通过props.onClick进行调用,且代码运行符合预期,想了解这一现象的原理。

CourseInput.js

import React, { useState } from "react";

import Button from "../../UI/Button/Button";
import "./CourseInput.css";

const CourseInput = (props) => {
  console.log(props);
  const [enteredValue, setEnteredValue] = useState("");

  const goalInputChangeHandler = (event) => {
    setEnteredValue(event.target.value);
  };

  const formSubmitHandler = (event) => {
    event.preventDefault();
    props.onAddGoal(enteredValue);
  };

  return (
    <form onSubmit={formSubmitHandler}>
      <div className="form-control">
        <label>Course Goal</label>
        <input type="text" onChange={goalInputChangeHandler} />
      </div>
      <Button type="submit">Add Goal</Button>
    </form>
  );
};

export default CourseInput;

Button.js

import React from "react";

import "./Button.css";

const Button = (props) => {
  return (
    <button type={props.type} className="button" onClick={props.onClick}>
      {props.children}
    </button>
  );
};

export default Button;

原理说明

  1. 原生HTML表单的默认行为:你给Button组件传递了type="submit",最终渲染出的原生<button>标签会继承这个type属性。在HTML规则里,type="submit"的按钮被点击时,会自动触发它所在<form>的submit事件,这是浏览器的原生行为,和你有没有手动绑定onClick无关。

  2. React对undefined事件绑定的处理:Button组件里写了onClick={props.onClick},但因为没有传递这个props,props.onClick的值是undefined。React在处理事件绑定的时候,如果绑定的是undefined,会自动忽略这个绑定操作,不会抛出错误,相当于这个onClick监听根本没被添加。

  3. 实际触发逻辑:点击按钮时,原生的表单提交行为生效,触发了<form>上绑定的onSubmit={formSubmitHandler},也就是你写的表单提交逻辑,所以代码运行符合预期。

如果验证这个逻辑,你可以把Button的type改成button,此时点击按钮就不会触发表单提交了——因为type="button"的按钮没有默认提交行为,这时候你才需要手动传递onClick函数来触发提交逻辑。

内容的提问来源于stack exchange,提问作者Samiul Karim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:48:15