[英]Unexpected keyword 'const' in componentDidMount, React
I'm trying to make a sticky header by getting DOM element and passing a function to it with componentDidMount, but get an error, that the 'const' is a Unexpected keyword:我试图通过获取 DOM 元素并使用 componentDidMount 将 function 传递给它来制作粘性 header,但得到一个错误,即“const”是一个意外的关键字:
component:零件:
class Header extends Component {
componentDidMount(){
window.addEventListener('scroll', () => {
const isTop = window.scrollY > 100,
const nav = document.getElementById('nav');
if (isTop) {
nav.classList.add('scrolled');
}else {
nav.classList.add('scrolled');
}
});
}
componentWillUnmount() {
window.removeEventListener('scroll');
}
render() {
return (<>
<header>
<nav class="nav" id="nav">
<ul class="header-list">
<li>
<img alt='phone' src={phonelogo} />
</li>
<li>123456789</li>
</ul>
<ul class="header-list">
<li>
<img alt='email' src={email} />
</li>
<li>123@gmail.com</li>
</ul>
</nav>
</header>
</>)
};
};
export default Header;
the error:错误:
Line 17:7: Parsing error: Unexpected keyword 'const'
15 | window.addEventListener('scroll', () => {
16 | const isTop = window.scrollY > 100,
> 17 | const nav = document.getElementById('nav');
| ^
18 | if (isTop) {
19 | nav.classList.add('scrolled');
20 | }else {
Though, it's probably better to use React refs, but it's still interesting what is going on here.虽然,使用 React refs 可能更好,但这里发生的事情仍然很有趣。
You have written:你写:
const isTop = window.scrollY > 100,
const nav = document.getElementById('nav');
You need to replace the comma with a simicolon at the end of line 16. Like so:您需要在第 16 行末尾用分号替换逗号。像这样:
const isTop = window.scrollY > 100;
const nav = document.getElementById('nav');
Line 16. You must remove the Comma or else reomve the const on line 17第 16 行。您必须删除逗号或删除第 17 行的 const
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.