Я разработал приложение с помощью responseJS, которое было запущено здесь. Исходный код приложения можно найти здесь. Приложение отлично работает в Chrome и firefox, но в Internet Explorer, Safari и во всех мобильных веб-браузерах я не могу отображать изображения при щелчке по полям при выборе второго режима.
App.js
import React, { Component } from 'react';
import './App.css';
import Status from'./components/Status';
import GameStatus from'./components/GameStatus';
const connery = require("./images/connery.svg");
const square = require("./images/square.svg");
class App extends Component {
constructor(props){
super(props)
this.state = {
board : Array(9).fill(null),
player : null,
winner : null,
gamemode : null,
/* array to store the ndex */
order_ndex : []
}
}
//Winning conditions
checkWinner(){
let winLines =
[
["0", "1", "2"],
["3", "4", "5"],
["6", "7", "8"],
["0", "3", "6"],
["1", "4", "7"],
["2", "5", "8"],
["0", "4", "8"],
["2", "4", "6"]
]
this.checkmatch(winLines)
}
//Checks if the current state matches the winning condition
checkmatch(winLines){
let board = this.state.board;
for (let index = 0; index < winLines.length; index++) {
const [a,b,c]=winLines[index];
if (board[a] && board[a] === board[b] && board[a] === board[c] ){
this.setState({
winner : this.state.player
})
this.state.winner = this.state.player;
}
}
if (!this.state.winner && !board.includes(null)){
this.setState({
winner : "None"
})
}
}
handleClick(index){
if (this.state.player && !this.state.winner){
let newBoard = this.state.board
if (this.state.board[index]===null){
newBoard[index] = this.state.player
/* push the last index into the array */
this.state.order_ndex.push(index)
this.setState({
board: newBoard,
player: this.state.player== = "X" ? "O" : "X"
})
this.checkWinner()
}
}
}
//Set the current state of Player
setPlayer(player){
this.setState({player})
}
//Set the current state of the Game mode
setGameMode(gamemode){
this.setState({gamemode})
}
//Renders the boxes into DOM
renderBoxes(){
const isFrontend = this.state.gamemode === "Frontenddevlandia";
return this.state.board.map(
(box, index) => (
<div
className = "box"
key = {index}
onClick = {() => {
this.handleClick(index);
}}
>
{box === "X" && isFrontend && <img src = {connery} alt = "X"/>}
{box === "O" && isFrontend && <img src = {square} alt = "O"/>}
{!isFrontend && box}
</div>
));
}
reset(){
this.setState({
board : Array(9).fill(null),
player : null,
winner : null,
setGameMode : null,
order_ndex : []
})
}
undo() {
let ndex = this.state.order_ndex.pop()
let newBoard = this.state.board
let prev = newBoard[ndex]
newBoard[ndex] = null
this.setState({
board: newBoard,
player: prev
})
}
render() {
return (
<div className = "container">
<h1>Tic Tac Toe</h1>
<GameStatus
gamemode = {this.state.gamemode}
setGameMode = {(e)=> this.setGameMode(e)}
/>
<Status
player = {this.state.player}
setPlayer = {(e) => this.setPlayer(e)}
gamemode = {this.state.gamemode}
winner = {this.state.winner}
/>
<div className = "board">
{this.renderBoxes()}
</div>
<div className = "btn">
<button className='reset' onClick = {() => this.reset()}>
{" "}
Reset{" "}
</button>
<div className = "divider"/>
<button
className='reset'
disabled = {this.state.winner}
onClick = {() => this.undo()}
>
{" "}
Undo{" "}
</button>
</div>
</div>
);
}
}
export default App;
Как видите, я использовал require("./images/connery.svg"), могу ли я знать, что делаю не так?
@ ThunD3eR У меня нет файла web.config.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Думаю, здесь есть две проблемы:
Вы ничего не сказали о размере вашего SVG-изображения. Как правило, вы должны, по крайней мере, включить атрибут viewBox в тег <svg>. Например:
<svg width = "250" height = "250" viewBox = "0 0 250 250" ... >
Другая проблема заключается в том, что Safari не особенно хорош в рендеринге SVG. Однако, как правило, лучше, если вы встраиваете их с тегом <iframe> или <object> вместо использования <img>. Например:
<object data = "image.svg" type = "image/svg+xml"></object>
Также убедитесь, что ваш сервер доставляет SVG-контент с правильным типом MIME (Content-Type: image / svg + xml), так как это тоже может вызвать проблемы.
Источник HTML:
<!DOCTYPE html>
<html>
<body>
<h1>My first SVG</h1>
<object data = "image.svg" type = "image/svg+xml"></object>
</body>
</html>
image.svg:
<?xml version = "1.0" encoding = "UTF-8" standalone = "no"?>
<svg width = "250" height = "250" viewBox = "0 0 250 250"
xmlns = "http://www.w3.org/2000/svg"
xmlns:xlink = "http://www.w3.org/1999/xlink">
<rect x = "50" y = "50" width = "100" height = "100" style = "fill:blue"></rect>
<rect id = "foo" x = "50" y = "150" width = "500" height = "500" style = "fill:green"></rect>
<image x = "50" y = "10" width = "200" height = "200" xlink:href = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg= = "></image>
</svg>
подробнее проверить ссылку https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/href
Атрибут viewBox был упомянут в теге <svg>, проверьте.
Добавьте метатег для Internet Explorer.
<meta http-equiv = "X-UA-Compatible" content = "IE=edge">
HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "X-UA-Compatible" content = "IE=edge">
</head>
<body>
<p>svg images</p>
</body>
</html>
Да, но он все равно не отображается в Safari или мобильных браузерах, а также в IE.
Я просто заменил изображения SVG на изображения PNG, и все заработало отлично. Были некоторые проблемы с изображениями SVG, когда я конвертировал их онлайн.
Здравствуйте, я знаю, что это был старый вопрос, но не могли бы вы подробнее рассказать, как вы его решили? У меня аналогичная проблема (stackoverflow.com/questions/59797732/…), и я новичок в React, поэтому я надеялся, что вы можете мне помочь :)
Проверьте свой web.config. Какой предел у вашего загрузчика файлов?