我对 reactjs 和 javascript 很陌生,我正在尝试弄清楚如何让这个简单的 js 代码在我的 reactjs 文件中工作。我希望文本在点击时变为红色。
我尝试过:创建外部js文件并使用Helmet导入它以插入标签
import React, { Component } from 'react';
import './about.css';
import logo from './S54 Logo 2.svg';
import { Helmet } from "react-helmet";
import aboutJS from './about';
export default class About extends Component {
render() {
return (
<div id="about-page">
<Helmet>
<script>
{'aboutJS'};
</script>
</Helmet>
<img id="about-page-logo-img" src={logo} />
<h2 id="mission-statement" onclick="myFunction()">
Catalog the World's Underrepresented Art so everyone can share in the enjoyable experience
</h2>
</div>
)
}
}
这是js文件
export function myFunction() {
document.getElementById("mission-statement").style.color = "red";
}
我还尝试将该 js 代码直接添加到脚本标记中,而不是导入文件,但这不起作用。
我尝试将我创建的外部 js 文件的标签放入我的 index.html 文件中,并在我的 reactjs 文件中调用该函数。
没有任何工作。我应该在哪里以及如何添加此代码?
Zelmi,您可以使用import { myFunction } from 'path/to/your/jsfile.js'
它允许您使用myFunction
组件所在的 JS 文件中的任何位置。
此外,使用onClick
而不是onclick
,用小心大括号{}
代替引号来包装您的函数""
import React, { Component } from 'react';
import './about.css';
import logo from './S54 Logo 2.svg';
import { myFunction } from 'path/to/your/jsfile.js'; //HERE
import { Helmet } from "react-helmet";
import aboutJS from './about';
export default class About extends Component {
render() {
return (
<div id="about-page">
<Helmet>
<script>
{'aboutJS'};
</script>
</Helmet>
<img id="about-page-logo-img" src={logo} />
<h2 id="mission-statement" onClick={myFunction}>
Catalog the World's Underrepresented Art so everyone can share in the enjoyable experience
</h2>
</div>
)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句