React Alert组件首字母大写函数出现Uncaught TypeError错误求助
问题解决
错误原因
你在调用字符串大写方法时出现了拼写错误:把toUpperCase()误写成了toUppererCase()(多了一个字母r),JavaScript中不存在toUppererCase这个方法,因此抛出了类型错误。
修正后的代码
import React from "react"; function Alert(props) { const capitalize = (word) => { const lower = word.toLowerCase(); let msg = lower.charAt(0).toUpperCase() + lower.slice(1); // 修正方法名拼写 return msg; }; return ( props.alert && ( <div className={`alert alert-${props.alert.type} alert-dismissible fade show`} role="alert"> <strong>{capitalize(props.alert.type)}</strong> : {props.alert.msg} </div> )); } export default Alert;
额外提示
如果后续遇到类似“XX is not a function”的错误,优先检查:
- 函数/方法名的拼写是否正确
- 调用该方法的变量是否为预期的数据类型(比如此处确保
word是字符串,避免非字符串调用toLowerCase())
内容的提问来源于stack exchange,提问作者mjshubham21
相关产品推荐
相关产品推荐

