Приложение ReactJS не работает в Localhost с традиционным синтаксисом тега JS-скрипта - PullRequest
0 голосов
/ 12 февраля 2019

Как я уже упоминал в вопросе, перейдите в этот JSFiddle и проверьте, что игра TicTacToe работает так, как и должно.

Теперь, если я поместу полный Javascript внутри "ReactScripts.js "и удалите ненужные операторы 'use strict' и включите их вместе с тем же CSS-кодом, который используется в скрипте, как показано ниже, он вообще не работает в браузере Localhost Firefox:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Tic Tac Toe Game</title>
        <link rel="stylesheet" type="text/css" href="index.css">
        <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
        <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    </head>
    <body>
        <noscript>You need to enable JavaScript to run this app.</noscript>
        <div id="root"></div>
        <script type="text/jsx" src="ReactScripts.js"></script>
        <script type="text/jsx">
            ReactDOM.render(<Game />, document.getElementById('root'));
        </script>
    </body>
</html>

Почемучто любая помощь приветствуется.

1 Ответ

0 голосов
/ 12 февраля 2019

На самом деле у меня все получилось, причина была совершенно иная, чем я думал, что я легко обнаружил, внимательно изучив, КАК jsfiddle работает при загрузке указанных библиотек и их зависимостей , даже если не указано.

Пожалуйста, ознакомьтесь с кодами ниже:

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta name="robots" content="noindex, nofollow">
        <meta name="googlebot" content="noindex, nofollow">
        <title>Tic Tac Toe Game</title>
        <link rel="stylesheet" type="text/css" href="mainstyle.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    </head>
    <body>
        <noscript>You need to enable JavaScript to run this app.</noscript>
        <div id="root"></div>
        <script type="text/jsx" src="react_scripts.js"></script>
        <script type="text/jsx">
            ReactDOM.render(<Game />, document.getElementById('root'));
        </script>
    </body>
</html>

CSS (mainstyle.css):

body {
    font: 24px'Century Gothic', Futura, sans-serif;
    margin: 20px;
}
ol,ul {
    padding-left: 30px;
}
.board-row:after {
    clear: both;
    content: '';
    display: table;
}
.status {
    margin-bottom: 10px;
}
.square {
    background: #fff;
    border: 1px solid #999;
    float: left;
    font-size: 24px;
    font-weight: bold;
    line-height: 34px;
    height: 54px;
    margin-right: -1px;
    margin-top: -1px;
    padding: 0;
    text-align: center;
    width: 54px;
}
.square--green {
    background: green;
}
.square:focus {
    outline: none;
}
.kbd-navigation .square:focus {
    background: #ddd;
}
.game {
    display: flex;
    flex-direction: row;
}
.game-info {
    margin-left: 20px;
}
.button {
    background-color: #555555;
    /* Green */
    border: none;
    color: #fff;
    padding: 5px 10px;
    text-align: center;
    text-decoration: none;
    font-size: 14px;
    cursor: pointer;
}
.button--green {
    background-color: #4caf50;
    color: #000;
    font-weight: bold;
}

JS Scripts (response_scripts.js)):

const calculateWinner = (squares) => {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
    ];
    for (let i = 0; i < lines.length; i += 1) {
        const [a, b, c] = lines[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            return {
                winner: squares[a],
                winnerRow: lines[i]
            };
        }
    }
    return {
        winner: null,
        winnerRow: null
    };
};
const getLocation = (move) => {
    const locationMap = {
        0: 'row: 1, col: 1',
        1: 'row: 1, col: 2',
        2: 'row: 1, col: 3',
        3: 'row: 2, col: 1',
        4: 'row: 2, col: 2',
        5: 'row: 2, col: 3',
        6: 'row: 3, col: 1',
        7: 'row: 3, col: 2',
        8: 'row: 3, col: 3',
    };
    return locationMap[move];
};
class Game extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            history: [{
                squares: Array(9).fill(null),
            }, ],
            currentStepNumber: 0,
            xIsNext: true,
        };
    }
    handleClick(i) {
        const history = this.state.history.slice(0, this.state.currentStepNumber + 1);
        const current = history[history.length - 1];
        const squares = current.squares.slice();
        if (calculateWinner(squares).winner || squares[i]) {
            return;
        }
        squares[i] = this.state.xIsNext ? 'X' : 'O';
        this.setState({
            history: history.concat([{
                squares,
                currentLocation: getLocation(i),
                stepNumber: history.length,
            }, ]),
            xIsNext: !this.state.xIsNext,
            currentStepNumber: history.length,
        });
    }
    jumpTo(step) {
        this.setState({
            currentStepNumber: step,
            xIsNext: step % 2 === 0,
        });
    }
    sortMoves() {
        this.setState({
            history: this.state.history.reverse(),
        });
    }
    render() {
        const {
            history
        } = this.state;
        const current = history[this.state.currentStepNumber];
        const {
            winner, winnerRow
        } = calculateWinner(current.squares);
        const moves = history.map((step, move) => {
            const currentLocation = step.currentLocation ? `(${step.currentLocation})` : '';
            const desc = step.stepNumber ? `Go to move #${step.stepNumber}` : 'Go to game start';
            const classButton = move === this.state.currentStepNumber ? 'button--green' : '';
            return ( < li key = {
                    step.stepNumber
                } > < button className = {
                    `${classButton} button`
                }
                onClick = {
                    () => this.jumpTo(move)
                } > {
                    `${desc} ${currentLocation}`
                } < /button>
        </li > );
        });
        let status;
        if (winner) {
            status = `Winner ${winner}`;
        } else if (history.length === 10) {
            status = 'Draw. No one won.';
        } else {
            status = `Next player: ${this.state.xIsNext ? 'X' : 'O'}`;
        }
        return ( < div className = "game" > < div className = "game-board" > < Board squares = {
                current.squares
            }
            winnerSquares = {
                winnerRow
            }
            onClick = {
                i => this.handleClick(i)
            }
            />
        </div > < div className = "game-info" > < div > {
                status
            } < /div>
          <button className="button" onClick={() => this.sortMoves()}>
            Sort moves
          </button > < ol > {
                moves
            } < /ol>
        </div > < /div>
    );
  }
}

class Board extends React.Component {
  createBoard(row, col) {
    const board = [];
    let cellCounter = 0;

    for (let i = 0; i < row; i += 1) {
      const columns = [];
      for (let j = 0; j < col; j += 1) {
        columns.push(this.renderSquare(cellCounter++));
      }
      board.push(<div key={i} className="board-row">{columns}</div > );
    }
    return board;
}
renderSquare(i) {
    const winnerClass = this.props.winnerSquares && (this.props.winnerSquares[0] === i || this.props.winnerSquares[1] === i || this.props.winnerSquares[2] === i) ? 'square--green' : '';
    return ( < Square winnerClass = {
            winnerClass
        }
        key = {
            i
        }
        value = {
            this.props.squares[i]
        }
        onClick = {
            () => this.props.onClick(i)
        }
        />
    );
  }

  render() {
    return <div>{this.createBoard(3, 3)}</div > ;
    }
}
const Square = props => ( < button className = {
        `${props.winnerClass} square`
    }
    onClick = {
        props.onClick
    } > {
        props.value
    } < /button>
);

Для загрузки и работы компонентов React требовалась только зависимость babel.js.

...