Как запустить проект JavaScript / Jquery в моем приложении React JS - PullRequest
0 голосов
/ 14 января 2020

Во-первых, простите меня за мой английский sh ... и мой код, я начал кодировать в июне прошлого года.

Я создаю свой младший портфель и хочу показать небольшую видеоигру с Jquery и Javascript.

Но скрипт не работает, например, все div, созданные скриптом, не отображаются. Несмотря на мои исследования и различные тесты, я не нашел никаких решений ..

Для достижений, которые я хочу отобразить, я выполняю динамическое отображение c в соответствии с количеством достижений.

My React js компонент

// == Import : npm
import React, { Component } from 'react';
import { Button } from 'evergreen-ui';
import Fade from 'react-reveal/Fade';
import * as jQuery from 'jquery';

// == Import : local
import './achievements.scss';
import reals from "src/data/reals";

class Achievements extends Component {

  state = {
    index : null
  }

  // Flip the card and display the frame or the projet
  showContent = (index, event) => {

    event.preventDefault();

    if (this.state.index == null) {
      this.setState({
        index : index 
      })
    } else {
      this.setState({
        index : null
      })
    }
  }

  render() {

    window.$ = jQuery;

    return (
      <div className="carousel">
        <Fade left>
          <span>Mes réalisations</span>
              {reals.map( (real)  => (  
                  <div className="carousel-card " key={real.index}>
                      {this.state.index !== real.index ? ( 
                      <>
                        <img className="carousel-img" src={real.image.src} alt={real.image.name}></img>
                        <p className="carousel-p">{real.description}</p>
                        <Button className="carousel-btn" onClick={() => this.showContent(real.index, event)}>Show me</Button>
                      </> )
                       : (
                      <>
                        {real.content}
                        <Button className="carousel-btn" onClick={() => this.showContent(real.index, event)}>Close</Button>
                       </>)}
                  </div>
              ))}
        </Fade>
      </div>
    );
  }
}

export default Achievements;

Мой массив объектов, соответствующих достижениям

// == Import : npm
import React, { Component } from 'react';

// == Import : local
import logoTindev from "src/data/images/logo-tindev.png";
import gameJs from "src/data/images/game-js.png";
import building from "src/data/images/building.jpg"

const reals = [
    {
        index : 1,
        name : "TinDev",
        image : {
            src : logoTindev,
            name : "logo Tindev"
        },
        description : "Réalisé lors du dernier mois de formation ; à la manière de Tinder, Tindev est une application de rencontres pour les passionnés du Web. Que ce soit pour travailler sur un projet en commun, trouver un job et pourquoi pas l\'amour.. Nous sommes partie d'une simple idée que nous avons fait grandir au travers des différentes étapes de conception d'une application WEB.Nous l\'avons programmé à l\'aide de React Js, Redux, Ajax et Bootstrap pour la partie Front (partie pour laquelle j\'étais le référent) et de Node.js, MySql et Express pour la partie Back.",
        content : <iframe className="carousel-content" width="  " height="315" src="https://www.youtube.com/embed/yjX809uYZKU" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
    },
    {
        index : 2,
        name : "Mini Video-Game",
        image : {
            src : gameJs,
            name : "Mini Video-Game"
        },
        description : "Mini-jeu dont le but est de partir d'un point A et d'arriver jusqu'au point B, ces deux derniers étant générés aléatoirement. Réalisé à l'aide de JavaSript et de Jquery.",
        content :
        <>
            <link rel="stylesheet" href="src/data/projects/Mini-Video-game/css/reset.css" />
            <link rel="stylesheet" href="src/data/projects/Mini-Video-game/css/style.css" />
            <div>   
                <div >
                    <div className="label">Your code</div>
                    <textarea id="userCode" placeholder="Use move forward / turn left / turn right (good luck !)"></textarea>
                    <button id="launchScript">Lancer le script</button>
                    <button id="launchNew">Nouvelle partie</button>

                </div>

                <div id="board">

                </div>
                <script src="src/data/projects/Mini-Video-game/css/app.js" async defer></script>

            </div>
        </>
    },
    {
        index : 3,
        name : "Chatroom",
        image : {
            src : building,
            name : "Chatroom"
        },
        description : "Chatroom permettant d'envoyer et de recevoir des messages instantanés. Réalisé à l'aide React, Redux et Socket.io.",
        content : <div className="carousel-content">Hello</div>
    }
]

export default reals;

My App . js файл:

var app = {

  init: function() {

    // Event listener
    $( "#launchScript" ).click(app.handleLaunchScriptButton);

    // Lancer une nouvelle partie sans rechargement de la page
    $( "#launchNew" ).on('click', function() {
      location.reload();
    });

    // Nombre aléatoire pour la case départ et d'arrivée
    app.ramdomNbStart = Math.floor(Math.random() * (23 - 0 + 1) + 0);
    app.ramdomNbEnd = Math.floor(Math.random() * (23 - 0 + 1) + 0);

    if (app.ramdomNbStart === app.ramdomNbEnd) {

      app.ramdomNbStart = Math.floor(Math.random() * (23 - 0 + 1) + app.ramdomNbEnd);
    }

    // Colonne de départ pour le curseur qui permettra de bien placer le curseur à la suite d'un moveFoward();
    if (app.ramdomNbStart >= 6 && app.ramdomNbStart <= 11) {
              app.column = app.ramdomNbStart - 6;
    } else if (app.ramdomNbStart >= 12 && app.ramdomNbStart <= 17) {
              app.column = app.ramdomNbStart - 12;
    } else if (app.ramdomNbStart >= 18 && app.ramdomNbStart <= 24) {
              app.column = app.ramdomNbStart - 18;
    } else {
              app.column = app.ramdomNbStart;
    }
    console.log(app.column);
    // Lancement
    app.drawBoard();

  },

  // Déclarer la méthode drawBoard() dans app permettant de dessiner la board
  drawBoard: function () {

    let parentContent = $("#board");

    // Créer les div avec les bonnes classes pour avoir ces 4 lignes
    for (let i = 1; i < 5; i++) {

      let childContent = $("<div>").addClass("cellRow").attr("id", "row"+[i]);

      parentContent.append(childContent);

            // Créer les div avec les bonnes classes pour avoir ces 6 colonnes
            for (let j = 0; j < 6; j++) {

              let littleChildContent = $("<div>").addClass("cell");

              childContent.append(littleChildContent);
            }

    }


        // Case de départ aléatoire
        $("div.cell:eq("+app.ramdomNbStart+")").addClass("cellStart");
        // et d'arrivée aléatoire
        $("div.cell:eq("+app.ramdomNbEnd+")").addClass("cellEnd");

        // Avec curseur / si pas déjà présent
        if (!$("div.cell").hasClass("cellCurrent")) 
        {
            $(".cellStart").addClass("cellCurrent cellCurrent-right");
        }



  },


  // Faire avancer le curseur
  moveForward: function() {

      // Si la position du curseur est à gauche
      if ($(".cellCurrent").hasClass("cellCurrent-left")) {
        console.log("1 moveFoward");
        $(".cellCurrent").prev().addClass("cellCurrent cellCurrent-left");
        $(".cellCurrent").next().removeClass("cellCurrent cellCurrent-left");

        if (app.column > 0){

          app.column--;
        }

      }

      // Si la position du curseur est en haut
      else if ($(".cellCurrent").hasClass("cellCurrent-top")) {
        console.log("2 moveFoward");
        $(".cellCurrent").parent().prev().children().eq(app.column).addClass("cellCurrent cellCurrent-top");
        $(".cellCurrent").parent().next().children().removeClass("cellCurrent cellCurrent-top");
      }

      // Si la position du curseur est à droite
      else if ($(".cellCurrent").hasClass("cellCurrent-right")) {
        console.log("3 moveFoward");
        $(".cellCurrent").next().addClass("cellCurrent cellCurrent-right");
        $(".cellCurrent").prev().removeClass("cellCurrent cellCurrent-right");

        if (app.column < 5){

          app.column++;
        }

      }

      // Si la position du curseur est en bas
      else  {
        console.log("4 moveFoward");
        $("div.cellCurrent").parent().next().children().eq(app.column).addClass("cellCurrent cellCurrent-bottom");
        $("div.cellCurrent").parent().prev().children().removeClass("cellCurrent cellCurrent-bottom");

      }
  },



    // Touner à droite
    turnRight: function() {


      // Si la position du curseur est à gauche
      if ($(".cellCurrent").hasClass("cellCurrent-left")) {
        console.log("1 turnRight");
        $(".cellCurrent").removeClass("cellCurrent-left").addClass("cellCurrent-top");

      }

      // Si la position du curseur est en haut
      else if ($(".cellCurrent").hasClass("cellCurrent-top")) {
        console.log("2 turnRight");
        $(".cellCurrent").removeClass("cellCurrent-top").addClass("cellCurrent-right");

      }

      // Si la position du curseur est à droite
      else if ($(".cellCurrent").hasClass("cellCurrent-right")) {
        console.log("3 turnRight");
        $(".cellCurrent").removeClass("cellCurrent-right").addClass("cellCurrent-bottom");

      }

      // Si la position du curseur est en bas
      else  {
        console.log("4 turnRight");
        $(".cellCurrent").removeClass("cellCurrent-bottom").addClass("cellCurrent-left");

      }

    },

    // Tourner à gauche 
    turnLeft: function() {

      // Si la position du curseur est à gauche
      if ($(".cellCurrent").hasClass("cellCurrent-left")) {
        console.log("1 turnLeft");
        $(".cellCurrent").removeClass("cellCurrent-left").addClass("cellCurrent-bottom");

      }

      // Si la position du curseur est en haut
      else if ($(".cellCurrent").hasClass("cellCurrent-top")) {
        console.log("2 turnLeft");
        $(".cellCurrent").removeClass("cellCurrent-top").addClass("cellCurrent-left");

      }

      // Si la position du curseur est à droite
      else if ($(".cellCurrent").hasClass("cellCurrent-right")) {
        console.log("3 turnLeft");
        $(".cellCurrent").removeClass("cellCurrent-right").addClass("cellCurrent-top");

      }

      // Si la position du curseur est en bas
      else {
        console.log("4 turnLeft");
        $(".cellCurrent").removeClass("cellCurrent-bottom").addClass("cellCurrent-right");

      }

  },

  handleLaunchScriptButton: function() {


    // TODO : get all lines as an array
    let codeLines = $("#userCode").val().split('\n');

    window.setTimeout(function() {
      app.codeLineLoop(codeLines, 0);
    }, 2000);
  },

  codeLineLoop: function(codeLines, index) {
    // Getting currentLine
    var currentLine = codeLines[index];
    console.log(currentLine);

    if (currentLine == "move forward") {

       app.moveForward();

    } else if (currentLine == "turn right") {

      app.turnRight();

    } else if (currentLine == "turn left") {

      app.turnLeft();

    } else {

        $("#userCode").val("");
        window.alert("Use move forward / turn left / turn right (good luck !)")
        return;
    }

    // Increment
    index++;

    // if still a line to interpret
    if (index < codeLines.length) {
      // Recall same method (=> make a loop)
      window.setTimeout(function() {
        app.codeLineLoop(codeLines, index);
      }, 1000);
    } else {
      window.setTimeout(function() {
        app.checkSuccess();
      }, 1000);
    }
  },

  checkSuccess: function() {
    // TODO display if the game is won or not
    if ($(".cellCurrent").hasClass("cellEnd")) {

      window.alert("You win bro !");

    } else {
      $("#userCode").val("");
      window.alert("Try again..!");

    }

  }
};

$( "#board" ).ready(app.init);

Заранее благодарен за помощь:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...