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

React中onClick报错:期望为函数却得到对象的问题求助

问题原因及修复方案

核心错误

你在SignIn组件里接收参数的方式错了。React函数组件的第一个参数是完整的props对象,不是单个属性。你现在写const SignIn = (signInWithGoogle) => { ... },相当于把整个props对象命名成了signInWithGoogle,所以绑定给onClick的是这个对象,不是你传入的函数,自然会报“期望onClick监听器是函数,却得到对象类型”的错误。

而且这个错误在组件渲染时就会触发,不需要等到点击——React在解析onClick属性时,会检查它的类型是否符合要求,发现是对象就直接报错了。

修复方法

有两种简单的修改方式:

方式1:解构props参数

直接从props对象里解构出你需要的函数:

import React from "react";

const SignIn = ({ signInWithGoogle }) => {
    return (
        <div>
            <button onClick={signInWithGoogle}>Sign in with google</button>
        </div>
    );
};

export default SignIn;

方式2:通过props对象访问属性

保留props参数,然后通过点语法获取函数:

import React from "react";

const SignIn = (props) => {
    return (
        <div>
            <button onClick={props.signInWithGoogle}>Sign in with google</button>
        </div>
    );
};

export default SignIn;

两种方式都能解决问题,选你习惯的写法就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:45:46