reactjs 尝试在react中使用Typed.js

yr9zkbsy  于 2023-01-17  发布在  React
关注(0)|答案(1)|浏览(186)

我试图在我的网站上使用Typed.js,我已经得到了许多错误,我找不到一种方法来修复它们。
我已经浏览了GitHub,我发现了完全相同的问题,我在文档中使用了该代码,错误仍然弹出。错误总是Expression Expected} expected,还有Unexpected token. Did you mean {'}?这里也是错误的图片。***这里是导致的错误:***errors

import "./App.css";
import Typed from "typed.js";
import { useEffect, useRef } from "react";

function HomePage() {
  return (
    <>
      <body>
        <div class="hero">
          <nav>
            <h2 class="logo">JAKEISTHATMAN.</h2>
            <ul>
              <li>
                <a href="#">Home</a>
              </li>
              <li>
                <a href="#">About</a>
              </li>
              <li>
                <a href="#">Services</a>
              </li>
              <li>
                <a href="./contact.js">Portfolio</a>
              </li>
            </ul>
            <button type="button">Contact</button>
          </nav>
        </div>
        <div class="container"></div>

        <div class="main-text">
          <h1>
            I'm a <span class="type"></span>
          </h1>
          <p>
            Also I work for <b>@no</b> media team!
          </p>
          <button type="button">Contact</button>
        </div>

        export default function Typed() {
    const TypedElement = useRef(null);

    useEffect(() => {
        if (!TypedElement.current) return;

        const typed = new Typed(TypedElement.current, {
            strings: [
                "string",
                "string2",
                "string3",
            ],
            startDelay: 300,
            typeSpeed: 100,
            backSpeed: 100,
            backDelay: 500,
            loop: true,
        });

        // Destroying
        return () => {
            typed.destroy();
        };
    }, []);
  
   return <span ref={TypedElement}></span>
}

      </body>
    </>
  );
}

export default HomePage;
jk9hmnmh

jk9hmnmh1#

首先,如果上面的代码示例是你的代码的真实样子,那么它将无法工作,因为你突然在html标签中使用了javascript,尝试用花括号将javascript括起来,让文件知道你正在输入javascript代码,如下所示:

<div>
  {console.log("this is javascript")}
</div>

第二,看起来你正在尝试定义一个叫做Typed的功能组件。至少,像你上面所做的那样在html标记中定义一个功能组件是很糟糕的组织(如果不是不可能,不确定,或者从来没有尝试过)。你应该在HomePage函数之外定义一个叫做Typed的功能组件,如下所示:

import "./App.css";
import Typed from "typed.js";
import { useEffect, useRef } from "react";

const Typed = ({args_if_necessary}) => {
  const typeTarget = useRef(null);

  useEffect(() => {
    const typed = new Typed(typeTarget.current, {
      strings: ["<i>First</i> sentence.", `use args ${args_if_necessary}`],
      typeSpeed: 40,
    });

    return () => {
      typed.destroy();
    };
  }, []);

  return <span ref={typeTarget} />;
};

function HomePage() {
    
  return (
    <>
      <body>
        <your-other-html />

        <Typed args_if_necessary={"something"} />

      </body>
    </>
  );
}

export default HomePage;

相关问题