React新手求助:组件传参时导入组件报错问题
解决React组件导入后无法用
<Component/>语法渲染的问题 问题根源
你在SingleComment.js里的导出逻辑有误:你导出的是组件函数执行后的React元素对象,而非组件函数本身。
看这段代码:
export default singleComment();
这里调用了singleComment(),直接返回了函数的执行结果(JSX编译后的对象),但React要求组件必须是可调用的函数/类,才能用<SingleComment/>这种JSX语法渲染。
修复步骤
修改SingleComment.js的导出语句,去掉括号,直接导出函数:
export default singleComment;
为什么两种渲染方式表现不同
{SingleComment}:此时SingleComment是已经执行好的React元素对象,相当于直接把现成的元素插入JSX,所以能显示,但这不是组件的正确用法——你没法给它传props,也无法复用。<SingleComment/>:React会尝试把它当作组件调用(等价于执行SingleComment()),但此时SingleComment是一个对象而非函数,因此触发了Element type is invalid错误。
扩展:正确使用组件传props
如果要练习props传递,可以修改组件函数接收props参数,然后在父组件中传入数据:
- 修改
SingleComment.js:
import React from "react"; const singleComment = (props) => { return ( <div className="comment"> <a href="/" className="avatar"> <img src={props.profile} alt="profile" /> </a> <div className="content"> <a href="/" className="author"> {props.author} </a> <div className="metadata"> <span className="date">{props.date}</span> </div> <div className="text">{props.text}</div> </div> </div> ); }; export default singleComment;
- 在
index.js中调用组件并传props:
import React from "react"; import ReactDOM from "react-dom"; import SingleComment from "./SingleComment.js"; const App = () => { return ( <div className="ui comments"> <SingleComment profile="https://i.imgur.com/1bX5QH6.jpg" author="Sarah" date="Today at 5:00PM" text="How are you?" /> </div> ); }; ReactDOM.render(<App />, document.querySelector("#root"));
内容的提问来源于stack exchange,提问作者Stuckoflo
相关产品推荐
相关产品推荐

