如何将这个HTML代码制作成React js组件来生成随机代码

问题描述 投票:0回答:0
import React, {  useEffect } from 'react';

const RandomCodeGenerator = () => {
  const [randomCode, setRandomCode] = useState('');
  const [isDownloadVisible, setDownloadVisible] = useState(false);

  // Function to generate a random code
  const generateRandomCode = () => {
    const code = Math.random().toString(36).substr(2, 15); // Change length as needed
    setRandomCode(code);
    setDownloadVisible(true);
  };

  // Function to generate a downloadable file
  const downloadFile = () => {
    const element = document.createElement('a');
    element.href = `data:text/plain;charset=utf-8,${encodeURIComponent(randomCode)}`;
    element.download = 'random_code.txt';
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  };

  // Use useEffect to run code on the client side
  useEffect(() => {
    generateRandomCode();
  }, []); // Empty dependency array means this effect runs once after the initial render on the client side

  return (
    <div className="bg-gray-200 p-8">
      <h1 className="text-3xl mb-6">Generate a random discount code</h1>
      <div className="bg-white p-4 rounded-md shadow-md mb-6">{`Code: ${randomCode}`}</div>
      <button
        id="generateRandomCode"
        className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        onClick={generateRandomCode}
      >
        Generate Random Code
      </button>
      {isDownloadVisible && (
        <a
          id="downloadLink"
          href="#"
          className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"
          onClick={downloadFile}
        >
          Download Code
        </a>
      )}
    </div>
  );
};

export default RandomCodeGenerator;

**我怎样才能把这个服务器组件变成客户端组件。它向我显示此错误: ─[C:\Users�97\Desktop\qrwebsite\qrwebsit

html reactjs generator
© www.soinside.com 2019 - 2024. All rights reserved.