我第一次尝试使用 Gatsby 来构建博客。我正在使用 Gatsby Starter Blog作为基地。
我想添加一些 javascript 来为一些文本设置动画,作为快速测试,我已将以下内容添加到我的 html.js
文件中:
<script
dangerouslySetInnerHTML={{
__html: `
var name = 'world';
console.log('Hello ' + name);
console.log('hey');
const phrases = [
'aaa',
'bbb',
'ccc'
];
const el = document.getElementById('bio__subtext');
el.innerHTML = 'hi';
`,
}}
/>
然而,这会在我的控制台中引发以下错误:(index):15 Uncaught TypeError: Cannot read property 'innerHTML' of null
ID 正确,存在于我的 Bio.js 文件中:
class Bio extends React.Component {
render() {
return (
<div id="bio">
<div className="bio_wrapper">
<img
src={profilePic}
alt={'NdW'}
/>
<p>
Hi, I'm Natalie!<br />
I <span id="bio__subtext"></span><br/>
<span className="about_button"><a href="/">Find out more</a></span>
<a href="#" target="_blank">GH</a>
<a href="#" target="_blank">TW</a>
</p>
</div>
</div>
)
}
}
我假设这是因为 JS 试图在 Bio.js 完成之前运行..但是我如何告诉 JS “等待”?如果我尝试将 JS 包含在 Bio.js 文件中,它将无法编译。
添加 document.addEventListener("DOMContentLoaded", function(event) {
也无济于事。
最佳答案
应该不需要像您尝试使用 document.getElementById('bio__subtext')
那样选择 DOM 中的任何内容。
您可以在需要变量的组件中声明变量,或者通过来自更高上下文(页面或其他组件)的 prop
将其传递到组件中。
class Bio extends React.Component {
render () {
const name = 'Natalie'
const phrases = [
'Cowabunga',
'Its Ninja Time',
'Booyakasha'
]
return (
<div id="bio">
Hi, I'm {name}!<br />
Some of my favourite phrases are:
<ul>
{phrases.map(phrase => <li>{phrase}</li>)}
</ul>
</div>
)
}
}
关于javascript - JS 不在 Gatsby 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53872441/