如何在React中使用脚本标签?



我是React的新手,我想尝试在我的React组件中加入一些纯Javascript。我有一个我想使用的脚本标签的html文件,但显然在React中它比添加一些脚本标签要复杂一些。从我所阅读的内容来看,我似乎需要学习JSX。无论哪种方式,这里是我想要使用的html代码片段,然后是我试图在React组件中使用它。

HTML工作代码:

<!-- grabs foo element (list itself) and sets a timeout of 1 second so we 
can toggle off the hidden text class -->
<script>
const text = document.querySelector("#foo");
setTimeout(() => {
text.classList.toggle("hidden-text");
}, 1000);
</script>
</body>

反应组件:

import React from 'react';
import { Link } from 'react-router-dom';
import './HeroSec.css';``
/* Need to figure out how to use Javascript tags in React Component
const Hello = () => {
return React.createElement(
'script'
)
}*/
function HeroSec(){
return(
<div className='hero-container'>

反应方式

我告诉你,Neo,当你正确使用React时,你不需要。查看这里的代码https://codesandbox.io/s/brave-bohr-vzp2h?file=/src/App.tsx

import { useEffect, setState } from 'react';
const App = () => {
const [show, setShow] = useState(false);
useEffect(() => {
setTimeout(() => {
setShow(true);
}, 1000);
}, []);
return (
<div>
<h1>My App</h1>
{show ? <p>Hidden Text</p> : null}
</div>
);
}

所以我们的想法是专注于更改单个呈现传递的逻辑,而不是更改特定的DOM元素。把重点放在变量状态上,不要担心弄乱DOM细节。调用setShow(true)告诉react自动重新渲染场景。

我个人喜欢codesandbox上的这些快速设置项目。我建议你试一试,不要担心设置问题。

下面是这个例子,你可以随意使用。

https://codesandbox.io/s/brave-bohr-vzp2h?file=/src/App.tsx

欢迎使用StackOverflow和React!React的伟大之处在于它是基于Javascript构建的。这意味着你可以将纯javascript函数作为应用程序的一部分。下面是一个简单的应用程序示例:

function App(){
const SomeObject = {title:'Amazing',val:42};
const SomeArray  = Object.entries(SomeObject);
const SomeResult = <PassVal passed={SomeArray} />;
// Javascript function
function PassVal(props){
const  value = props.passed[0][1];
return value;
}

return (
<>
<p>{SomeResult}</p>
</>
)
}
ReactDOM.render(
<App  />,
document.getElementById('root')
);
这里有一些代码将加载一个外部脚本:

function App() {
const status = useScript(
'https://pm28k14qlj.codesandbox.io/test-external-script.js'
);

return (
<div>
<div>
Script status: <b>{status}</b>
</div>
{status === "ready" && (
<div>
Script function call response: <b>{TEST_SCRIPT.start()}</b>
</div>
)}
</div>
);
}

// Hook
function useScript(src) {
// Keep track of script status ("idle", "loading", "ready", "error")
const [status, setStatus] = React.useState(src ? "loading" : "idle");

React.useEffect(
() => {
// Allow falsy src value if waiting on other data needed for
// constructing the script URL passed to this hook.
if (!src) {
setStatus("idle");
return;
}

// Fetch existing script element by src
// It may have been added by another intance of this hook
let script = document.querySelector(`script[src="${src}"]`);

if (!script) {
// Create script
script = document.createElement("script");
script.src = src;
script.async = true;
script.setAttribute("data-status", "loading");
// Add script to document body
document.body.appendChild(script);

// Store status in attribute on script
// This can be read by other instances of this hook
const setAttributeFromEvent = (event) => {
script.setAttribute(
"data-status",
event.type === "load" ? "ready" : "error"
);
};

script.addEventListener("load", setAttributeFromEvent);
script.addEventListener("error", setAttributeFromEvent);
} else {
// Grab existing script status from attribute and set to state.
setStatus(script.getAttribute("data-status"));
}

// Script event handler to update status in state
// Note: Even if the script already exists we still need to add
// event handlers to update the state for *this* hook instance.
const setStateFromEvent = (event) => {
setStatus(event.type === "load" ? "ready" : "error");
};

// Add event listeners
script.addEventListener("load", setStateFromEvent);
script.addEventListener("error", setStateFromEvent);

// Remove event listeners on cleanup
return () => {
if (script) {
script.removeEventListener("load", setStateFromEvent);
script.removeEventListener("error", setStateFromEvent);
}
};
},
[src] // Only re-run effect if script src changes
);

return status;
}
ReactDOM.render(
<App  />,
document.getElementById('root')
);

最新更新