通过电话电子邮件将一键登录与电话集成 - 将 html 和 javascript 代码转换为 React JS

问题描述 投票:0回答:1

我正在学习 React JS,而且是新手。 我有以下代码可在我的网站上将一键登录与电话(来自电话.电子邮件)集成。此按钮将验证 OTP 并将验证后的号码发送回我的网站。

<div id="pheIncludedContent"></div>
<script src="https://auth.phone.email/login_automated_v1_2.js"></script>
<script>
  var reqJson='{"success_url":"","client_id":"XXXXXXXXXXXXXXXXX","button_text":"Sign in with Phone","email_notification":"icon","button_position":"left"}';
log_in_with_phone(reqJson);
</script>

我正在尝试将其转换为 React JS 代码并尝试将其集成到我的网站上。 以下是我的 React JS 组件代码

import React, { useEffect } from 'react';

const SigninPhone = () => {
  useEffect(() => {
    // Create a script element
    const script = document.createElement('script');
    
    // Set the src attribute to the external script URL
    script.src = 'https://auth.phone.email/login_automated_v1_2.js';
    
    // Append the script element to the document body
    document.body.appendChild(script);
    
    // Define the request JSON object
    const reqJson = {
      success_url: '',
      client_id: 'XXXXXXXXXXXXXXXXX',
      button_text: 'Sign in with Phone',
      email_notification: 'icon',
      button_position: 'left'
    };
    
    // Call the log_in_with_phone function with the request JSON object
    window.log_in_with_phone(JSON.stringify(reqJson));

    // Clean up function to remove the script element when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); // Empty dependency array to ensure useEffect runs only once

  return <div id="pheIncludedContent"></div>;
};

export default SigninPhone;

但是我收到类似“Uncaught TypeError: window.log_in_with_phone is not a function”的错误 log_in_with_phone 函数位于 https://auth.phone.email/login_automated_v1_2.js 这个脚本中。

请帮我解决这个问题

javascript reactjs single-sign-on
1个回答
0
投票

我认为问题是您在加载脚本之前尝试使用它。试试这个:

useEffect(() => {
    // Create a script element
    const script = document.createElement('script');
    
    // Set the src attribute to the external script URL
    script.src = 'https://auth.phone.email/login_automated_v1_2.js';
    
    // Append the script element to the document body
    document.body.appendChild(script);
    
    // Define the request JSON object
    const reqJson = {
      success_url: '',
      client_id: 'XXXXXXXXXXXXXXXXX',
      button_text: 'Sign in with Phone',
      email_notification: 'icon',
      button_position: 'left'
    };

    script.onload = () => {
        window.log_in_with_phone(JSON.stringify(reqJson));
    }
     


    

    // Clean up function to remove the script element when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []);
© www.soinside.com 2019 - 2024. All rights reserved.