Javascript-форум (https://javascript.ru/forum/)
-   Библиотеки/Тулкиты/Фреймворки (https://javascript.ru/forum/library-toolkit-framework/)
-   -   Изменение backgroundcolor DIVa в React (https://javascript.ru/forum/library-toolkit-framework/78936-izmenenie-backgroundcolor-diva-v-react.html)

Malleys 25.11.2019 00:42

Цитата:

Сообщение от рони
наверняка этот код в целом можно сократить и написать рациональнее.

Да, можно функции в методе render можно объявить как методы и использовать состояние вместо того, чтобы искать элементы в DOM (как это всё время делают в jQuery). Меня вообще удивило то, что вы ищете элемент, когда вы можете поменять всё, что угодно, это ведь render!

Malleys 25.11.2019 01:05

Примерно так...
<html>
<head>
	<title></title>
	<style type="text/css">
		.cell{
			height: 50px;
			width: 50px;
			background-color: #FFFF00;
		}
		.game > div {
			width: 250px;
			display: flex;
			flex-wrap: wrap;
		}
	</style>
</head>
<body>
    <div id="root"></div>
    <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>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
    <script type="text/babel">

const { createElement, Component } = React;

class Game extends Component {
	state = {
		randomCell: null,
		greenCells: []
	}

	duel = Array.from(new Array(25), (_, i) => i);

	setGreen = () => {
		this.setState({
			randomCell: null,
			greenCells: this.state.greenCells.concat(this.state.randomCell)
		});
	};

	numRandom = () => {
		const randomCell = Math.floor(25 * Math.random());
		this.setState({ randomCell });
	};

	render() {
		const { randomCell, greenCells } = this.state;
		return <div className="game">
			<div>
				<button onClick={this.numRandom}>Play</button>
			</div>

			<div>{
				this.duel.map(i => {
					const style = {};
					if(greenCells.includes(i))
						style.backgroundColor = "green";
					if(randomCell === i)
						style.backgroundColor = "blue";
					return <div
						className="cell"
						style={style}
						onClick={randomCell === i ? this.setGreen : null}
					></div>
				})
			}</div>
		</div>
	}
}

ReactDOM.render(<Game />, document.getElementById("root"))

    </script>
</body>
</html>

рони 25.11.2019 08:36

Цитата:

Сообщение от Malleys
что угодно, это ведь render!

о великий, если б я знал короткую дорогу, известную тебе, а пока мне ваша фраза ни о чём не говорит, спасибо за пример, жаль не берёте в ученики. :)

djekokma 25.11.2019 10:55

Спасибо

рони 25.11.2019 10:57

react игрушка продолжение
 
:) :write:
сделай поле зелёным!

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        .cell{
            height: 50px;
            width: 50px;
            background-color: #FFFF00;
        }
        .game > div {
            width: 250px;
            display: flex;
            flex-wrap: wrap;
        }
    </style>
</head>
<body>
    <div id="root"></div>
    <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>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
    <script type="text/babel">

const { createElement, Component } = React;

class Game extends Component {
    state = {
        randomCell: null,
        greenCells: new Set()
    }

    duel = Array.from(new Array(25), (_, i) => i);

    setGreen = () => {
        this.setState({
            randomCell: null,
            greenCells: this.state.greenCells.add(this.state.randomCell)
        });

    };

    numRandom = () => {
        const {greenCells} = this.state;
        const freeCell = this.duel.filter(i => !greenCells.has(i))
        const randomCell = freeCell[Math.floor(freeCell.length * Math.random())];
        this.setState({ randomCell });
        clearTimeout(this.timer);
        this.timer = setTimeout(this.numRandom, 1000);
    };

    render() {
        const { randomCell, greenCells } = this.state;
        if(greenCells.size == this.duel.length) return <h1>Game over</h1>;
        return <div className="game">
            <div>
                <button onClick={this.numRandom}>Play</button>
            </div>

            <div>{
                this.duel.map(i => {
                    const style = {};
                    if(greenCells.has(i))
                        style.backgroundColor = "green";
                    if(randomCell === i)
                        style.backgroundColor = "blue";
                    return <div
                        className="cell"
                        style={style}
                        onClick={randomCell === i ? this.setGreen : null}
                    ></div>
                })
            }</div>
        </div>
    }
}

ReactDOM.render(<Game />, document.getElementById("root"))

    </script>
</body>
</html>

djekokma 25.11.2019 11:42

Шикарно. Спасибо Вам, великие Профессора.

SuperZen 25.11.2019 13:28

import React from 'react'
import './App.css'

const CELL_COUNT = 25

function App() {
  const [cells] = React.useState(Array.from({ length: CELL_COUNT }, (_, i) => i))
  const [randomCell, setRandomCell] = React.useState(null)
  const playClick = () => setRandomCell(parseInt(Math.random() * CELL_COUNT))
  const greenClick = () => setRandomCell(null)

  return (
    <div className="game">
      <div>
        <button onClick={playClick}>Play</button>
      </div>
      <div>
        {cells.map((cell, idx) => <button
          key={cell}
          className={idx === randomCell ? 'cell random' : 'cell'}
          onClick={randomCell && greenClick}
        >{cell}</button>)}
      </div>
    </div>
  )
}

export default App

djekokma 26.11.2019 09:44

SuperZen,
Спасибо большущее


Часовой пояс GMT +3, время: 01:45.