我正在学习React,状态和道具的想法是相当新的。目前我正在尝试创建一个呈现一些SideNavButton组件的SideNav组件。这是我尝试将道具传递给子组件的第一次尝试,我不断得到这个看起来像这样的无用错误:
Syntax error: ./components/side-nav.js: Unexpected token, expected , (43:8)
41 | <SideNavButton button={button} />
42 | );
>43| });
.. | ^
44 | );
45 | }
46 |
我老老实实地认为这甚至没有指出问题。我会发布我的代码,如果有什么我可以做得更好,请随时告诉我。
./ index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import SideNav from './components/side-nav';
const App = () => {
return (
<div>
<SideNav />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
./组件/侧nav.js
import React, { Component } from 'react';
import SideNavButton from './side-nav-button';
class SideNav extends Component {
constructor(props) {
super(props);
this.state = {
navButtons: [
{
label: "Profile",
icon: "fas fa-user",
location: "#!"
}, {
label: "Experience",
icon: "fas fa-book",
location: "#!"
}, {
label: "Education",
icon: "fas fa-university",
location: "#!"
}, {
label: "Technology",
icon: "fas fa-code",
location: "#!"
}, {
label: "Connect",
icon: "fas fa-share-alt",
location: "#!"
}
]
};
}
renderButtons() {
return(
this.state.navButtons.map(button => {
return(
<SideNavButton button={button} />
);
});
);
}
render(
return (
<ul className="side-nav">
{renderButtons();}
</ul>
);
);
}
export default SideNav;
./组件/侧NAV-button.js
import React from 'react';
const SideNavButton = ({button}) => {
return(
<li key={button.label}>
<a href={button.location}>
<i className={button.icon}></i>{button.label}
</a>
</li>
);
}
export default SideNavButton;
答案 0 :(得分:3)
side-nav.js存在一些问题,请尝试使用此更正后的代码段
class SideNav extends Component {
constructor(props) {
super(props);
this.state = {
navButtons: [
{
label: "Profile",
icon: "fas fa-user",
location: "#!"
},
{
label: "Experience",
icon: "fas fa-book",
location: "#!"
},
{
label: "Education",
icon: "fas fa-university",
location: "#!"
},
{
label: "Technology",
icon: "fas fa-code",
location: "#!"
},
{
label: "Connect",
icon: "fas fa-share-alt",
location: "#!"
}
]
};
}
renderButtons() {
return this.state.navButtons.map(button => {
return <SideNavButton button={button} />;
});
}
render() {
return <ul className="side-nav">{this.renderButtons()}</ul>;
}
}
export default SideNav;
我更正了 renderButtons()和 render(){} 方法
请在Link
中找到您的代码答案 1 :(得分:1)
请阅读此class
定义参考,并附带示例:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
方法定义没有分号。所以删除所有这些。
类没有consts。 Consts可以是方法/函数,但不能是类中的顶级。
您可以将const buttons = ...
转换为方法:buttons() { return ...; }