我第一次尝试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“等待”呢?如果我尝试在Bio.js文件中包含JS,它将无法编译。
添加document.addEventListener("DOMContentLoaded", function(event) {
也无济于事。
答案 0 :(得分:1)
不需要像在尝试使用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>
)
}
}