如何在React JS中加载脚本?脚本不起作用

时间:2019-12-23 05:15:23

标签: javascript reactjs

我想使用https://websitebeaver.com/insanely-simple-webrtc-video-chat-using-firebase-with-codepen-demo中的视频聊天作为回应。当我尝试使用css + js + html时,脚本运行良好(无任何语法) 但是我转换为React后脚本不起作用

script.js文件位于\ chatting \ public \ js \ script.js

和Video.js文件位于\ chatting \ src \ components \ Messages \ Video.js

Video.js(我在单击按钮,模式打开时做到了这一点,然后进行了视频通话)

import React from 'react';
import { Modal, Icon } from 'semantic-ui-react';

class Video extends React.Component {
  componentDidMount() {
    const script = document.createElement('script');

    script.src = '../../../public/js/script.js';
    script.async = true;

    document.body.appendChild(script);
  }

  render() {
    return (
      <Modal trigger={<Icon name="video camera" color="grey" />}>
        <Modal.Header>VideoCall</Modal.Header>
        <Modal.Content image>
          <div className="videoChat">
            <link rel="stylesheet" type="text/css" href="css/style.css" />
            <video
              id="yourVideo"
              autoPlay
              muted
              playsInline
              className="videoChat"
            />
            <video
              id="friendsVideo"
              autoPlay
              playsInline
              className="videoChat"
            />
            <br />
            <button
              onclick="showFriendsFace()"
              type="button"
              className="btn btn-primary btn-lg"
            >
              <span
                className="glyphicon glyphicon-facetime-video"
                aria-hidden="true"
              />{' '}
              Call
            </button>
          </div>
        </Modal.Content>
      </Modal>
    );
  }
}

export default Video;

script.js

var firebaseConfig = {
  apiKey: 'I wrote this',
  authDomain: 'I wrote this',
  databaseURL: 'I wrote this',
  projectId: 'I wrote this',
  storageBucket: 'I wrote this',
  messagingSenderId: 'I wrote this',
  appId: 'I wrote this',
  measurementId: 'I wrote this'
};

firebase.initializeApp(firebaseConfig);

var database = firebase.database().ref();
var yourVideo = document.getElementById('yourVideo');
var friendsVideo = document.getElementById('friendsVideo');
var yourId = Math.floor(Math.random() * 1000000000);

var servers = {
  iceServers: [
    { urls: 'stun:stun.services.mozilla.com' },
    { urls: 'stun:stun.l.google.com:19302' },
    {
      urls: 'turn:numb.viagenie.ca',
      credential: 'I wrote this',
      username: 'I wrote this'
    }
  ]
};
var pc = new RTCPeerConnection(servers);
pc.onicecandidate = event =>
  event.candidate
    ? sendMessage(yourId, JSON.stringify({ ice: event.candidate }))
    : console.log('Sent All Ice');
pc.onaddstream = event => (friendsVideo.srcObject = event.stream);

function sendMessage(senderId, data) {
  var msg = database.push({ sender: senderId, message: data });
  msg.remove();
}

function readMessage(data) {
  var msg = JSON.parse(data.val().message);
  var sender = data.val().sender;
  if (sender != yourId) {
    if (msg.ice != undefined) pc.addIceCandidate(new RTCIceCandidate(msg.ice));
    else if (msg.sdp.type == 'offer')
      pc.setRemoteDescription(new RTCSessionDescription(msg.sdp))
        .then(() => pc.createAnswer())
        .then(answer => pc.setLocalDescription(answer))
        .then(() =>
          sendMessage(yourId, JSON.stringify({ sdp: pc.localDescription }))
        );
    else if (msg.sdp.type == 'answer')
      pc.setRemoteDescription(new RTCSessionDescription(msg.sdp));
  }
}

database.on('child_added', readMessage);

function showMyFace() {
  navigator.mediaDevices
    .getUserMedia({ audio: true, video: true })
    .then(stream => (yourVideo.srcObject = stream))
    .then(stream => pc.addStream(stream));
}

function showFriendsFace() {
  pc.createOffer()
    .then(offer => pc.setLocalDescription(offer))
    .then(() =>
      sendMessage(yourId, JSON.stringify({ sdp: pc.localDescription }))
    );
}

和index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />
    <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
    <script src="js/script.js"></script>

    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
    <script src="js/script.js"></script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

componentDidMount()生命周期方法通常用于从API提取数据,而不是导入js文件。只需将您的script.js导入Video.js。您还应该在script.js中导出所需的函数,然后可以通过添加第一个指定的名称在类中调用函数。在下面的代码中,我仅从script.js中导出showFriendsFace(),并在Video.js构造函数中将其调用:

import React from 'react';
import { Modal, Icon } from 'semantic-ui-react';
import Script from './script'


class Video extends React.Component {
  constructor(){
      super();

      Script.showFriendsFace();
  }

  render() {
    return (
      //your return code
    );
  }
}

export default Video;

和script.js应该看起来像这样:

//your script codes

function showFriendsFace() {
  console.log("Hello World!");
}

export default {showFriendsFace};