如何在 React 中使用脚本标签?
How to use script tags in 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'>
欢迎使用 Whosebug 和 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')
);
反应方式
“我告诉你 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.io 上的这些快速设置项目,并鼓励您尝试一下,避免先担心设置问题。
这是下面的示例,请随意使用它。
我是 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'>
欢迎使用 Whosebug 和 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')
);
反应方式
“我告诉你 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.io 上的这些快速设置项目,并鼓励您尝试一下,避免先担心设置问题。
这是下面的示例,请随意使用它。