0

我对 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'>
4

2 回答 2

0

反应方式

“我告诉你 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 上的快速设置项目,并鼓励你尝试一下,避免为了让自己先适应而担心设置。

这是下面的示例,您可以随意使用它。

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

于 2021-03-09T14:43:21.470 回答
0

欢迎使用 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')
);
于 2021-03-09T02:53:35.487 回答