【问题标题】:Need to import a plain javascript file to react需要导入一个普通的 javascript 文件来做出反应
【发布时间】:2021-06-08 16:58:45
【问题描述】:

我正在尝试转换 HTML、CSS 和 JS 组件以做出反应。我很容易使用 HTML 和 CSS,但遇到 JS 问题。我尝试使用 react-helmet 但出现错误

Cannot read property 'addEventListener' of null

react.js 文件:

import React,{ Component }from 'react'
import { Helmet } from 'react-helmet'
import './ContactForm.css'

export default class ContactForm extends Component {
    

    render() {
        return (
            <>
                <section>
                    <div className="container">
                        <form action="https://formsubmit.co/my@myemail.com" method="POST" id="my-form"> 
                                <div className="form-group">
                                    <label for="firstName"> First Name</label>
                                    <input type="text" id="firstName" name="firstName" />
                                </div>
    
                                <div className="form-group">
                                    <label for="latsName">Last Name</label>
                                    <input type="text" id="lastName" name="lastName" />
                                </div>
    
                                <div className="form-group">
                                    <label for="email">Email</label>
                                    <input type="email" id="email" name="email" />
                                </div>
    
                                <div className="form-group">
                                    <label for="massage">Massage</label>
                                    <textarea name="massage" id="massage" cols="30" rows="10"></textarea>
                                </div>
                                <button type="submit">Submit</button>
                        </form>   
                    </div>
                    <div id="status"></div>
                </section>
                <Helmet>
                    <script src="./main.js"></script>
                </Helmet>
                
            </>
            
           
        )
    }
}

原始 HTML/CSS/JS:

window.addEventListener("DOMContentLoaded", function () {
  // get the form elements defined in your form HTML above

  var form = document.getElementById("my-form");
  // var button = document.getElementById("my-form-button");
  var status = document.getElementById("status");

  // Success and Error functions for after the form is submitted

  function success() {
    form.reset();
    status.classList.add("success");
    status.innerHTML = "Thanks!";
  }

  function error() {
    status.classList.add("error");
    status.innerHTML = "Oops! There was a problem.";
  }

  // handle the form submission event

  form.addEventListener("submit", function (ev) {
    ev.preventDefault();
    var data = new FormData(form);
    ajax(form.method, form.action, data, success, error);
  });
});

// helper function for sending an AJAX request

function ajax(method, url, data, success, error) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.setRequestHeader("Accept", "application/json");
  xhr.onreadystatechange = function () {
    if (xhr.readyState !== XMLHttpRequest.DONE) return;
    if (xhr.status === 200) {
      success(xhr.response, xhr.responseType);
    } else {
      error(xhr.status, xhr.response, xhr.responseType);
    }
  };
  xhr.send(data);
}
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  font-family: "Montserrat";
}
section {
  height: 100vh;
  width: 100%;
  background-color: aliceblue;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.container {
  width: 90%;
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  box-shadow: 0px 0px 20px #00000010;
  background-color: white;
  border-radius: 8px;
  margin-bottom: 20px;
}
.form-group {
  width: 100%;
  margin-top: 20px;
  font-size: 20px;
}
.form-group input,
.form-group textarea {
  width: 100%;
  padding: 5px;
  font-size: 18px;
  border: 1px solid rgba(128, 128, 128, 0.199);
  margin-top: 5px;
}

textarea {
  resize: vertical;
}
button[type="submit"] {
  width: 100%;
  border: none;
  outline: none;
  padding: 20px;
  font-size: 24px;
  border-radius: 8px;
  font-family: "Montserrat";
  color: rgb(27, 166, 247);
  text-align: center;
  cursor: pointer;
  margin-top: 10px;
  transition: 0.3s ease background-color;
}
button[type="submit"]:hover {
  background-color: rgb(214, 226, 236);
}
#status {
  width: 90%;
  max-width: 500px;
  text-align: center;
  padding: 10px;
  margin: 0 auto;
  border-radius: 8px;
}
#status.success {
  background-color: rgb(211, 250, 153);
  animation: status 4s ease forwards;
}
#status.error {
  background-color: rgb(250, 129, 92);
  color: white;
  animation: status 4s ease forwards;
}
@keyframes status {
  0% {
    opacity: 1;
    pointer-events: all;
  }
  90% {
    opacity: 1;
    pointer-events: all;
  }
  100% {
    opacity: 0;
    pointer-events: none;
  }
}
<section>
  <div class="container">
    <form action="https://formspree.io/mbjzbwaj" method="POST" id="my-form">

      <div class="form-group">
        <label for="firstName"> First Name</label>
        <input type="text" id="firstName" name="firstName">
      </div>

      <div class="form-group">
        <label for="latsName">Last Name</label>
        <input type="text" id="lastName" name="lastName">
      </div>

      <div class="form-group">
        <label for="email">Email</label>
        <input type="email" id="email" name="email">
      </div>

      <div class="form-group">
        <label for="massage">Massage</label>
        <textarea name="massage" id="massage" cols="30" rows="10"></textarea>
      </div>

      <button type="submit">Submit</button>
    </form>
  </div>
  <div id="status"></div>
</section>

你可以在https://codepen.io/Web_Cifar/pen/gOrrPpO找到这个js文件 我需要那个普通的 js 文件来响应。

【问题讨论】:

    标签: javascript html css reactjs import


    【解决方案1】:

    React 是一个 javaScript 库 => 你可以将 JavaScript 代码直接插入到 React 中。

    <script src="./main.js"></script>   //--> is HTML's way to import a JS file
    

    在你的情况下,你需要格式化你的 JS 代码才能正常使用 React。

    示例(带有功能组件和钩子):

    import React, { useState } from "react";
    import "./ContactForm.css";
    
    export default function ContactForm() {
       const [formData, setFormData] = useState({
        firstName: "",
        lastName: "",
        email: "",
        massage: ""
      });
    
      const updateFormData = (e) =>
        setFormData({
          ...formData,
          [e.target.name]: e.target.value
        });
    
      const submitForm = (e) => {
        e.preventDefault();
        console.log(formData);
        fetch("https://formspree.io/mbjzbwaj", {
          method: "POST",
          body: JSON.stringify({ formData }),
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
          }
        })
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
      };
    
      const { firstName, lastName, email, massage } = formData;
    
      return (
        <section>
          <div className="container">
            <form id="my-form" onSubmit={submitForm}>
              <div className="form-group">
                <label htmlFor="firstName"> First Name</label>
                <input
                  type="text"
                  id="firstName"
                  name="firstName"
                  value={firstName}
                  onChange={(e) => updateFormData(e)}
                />
              </div>
    
              <div className="form-group">
                <label htmlFor="lastName">Last Name</label>
                <input
                  type="text"
                  id="lastName"
                  name="lastName"
                  value={lastName}
                  onChange={(e) => updateFormData(e)}
                />
              </div>
    
              <div className="form-group">
                <label htmlFor="email">Email</label>
                <input
                  type="email"
                  id="email"
                  name="email"
                  value={email}
                  onChange={(e) => updateFormData(e)}
                />
              </div>
    
              <div className="form-group">
                <label htmlFor="massage">Massage</label>
                <textarea
                  name="massage"
                  id="massage"
                  cols="30"
                  rows="10"
                  value={massage}
                  onChange={(e) => updateFormData(e)}
                ></textarea>
              </div>
              <button type="submit">Submit</button>
            </form>
          </div>
         </section>
      );
    }
    

    演示:stackblitz


    编辑

    要将 Formspree 与 React 一起使用,您必须使用特定的钩子,而且它非常简单......(文档 here

    首先你需要导入formspree

    npm i @formspree/react
    

    ContactForm.js

    import React from 'react';
    import { useForm } from '@formspree/react';
    
    export default function ContactForm() {
      const [state, handleSubmit] = useForm('######'); // hash id
      if (state.succeeded) {
        return <div>Sucess!</div>;
      }
      return (
        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label htmlFor="firstName"> First Name</label>
            <input type="text" id="firstName" name="firstName" />
          </div>
    
          <div className="form-group">
            <label htmlFor="lastName">Last Name</label>
            <input type="text" id="lastName" name="lastName" />
          </div>
    
          <div className="form-group">
            <label htmlFor="email">Email</label>
            <input type="email" id="email" name="email" />
          </div>
    
          <div className="form-group">
            <label htmlFor="massage">Massage</label>
            <textarea name="massage" id="massage" cols="30" rows="10"></textarea>
          </div>
          <button type="submit" disabled={state.submitting}>
            Submit
          </button>
        </form>
      );
    }
    
    • 您将在“表单详细信息”、“集成”选项卡中找到哈希 ID。 在您的示例中,您有“...formspree.io/mbjzbwaj”(hash id

    【讨论】:

    【解决方案2】:

    在 React 中,事件处理和其他功能有些不同。

    您可以像这样将事件与处理程序链接:

    <button onClick={handleClick}>CLICK</button>
    

    onClick 是事件,handleClick 是处理函数。

    在你的渲染函数之上,你可以像这样创建一个处理程序:

    const handleClick = () => {
      console.log("Clicked!");
      // do some functionality... 
    }
    

    您也可以通过(e)访问该活动

    const handleClick = (e) => {
      e.preventDefault(); // prevent the default action
      console.log("Clicked!");
      // do some functionality... 
    }
    

    如果您想将代码转换为 React,我建议您像这样尝试并查看 documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2020-12-01
      • 1970-01-01
      • 2016-07-09
      • 2016-12-08
      • 1970-01-01
      • 2017-12-06
      相关资源
      最近更新 更多