cannot add property 0 object is not extensible React.js 84 строка
Explosion={this.Explosion} если пытаюсь изменить состояние страничка падает, но если делаю там другие манипуляции (по типу консоллога) то все работает
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Mine from "./images/mine.png";
var N = 10;
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
function Fill(arr){
for(var i = 0; i < N; i++){
arr[i] = [];
for(var j = 0; j < N; j++){
if(getRandomArbitrary(0,101) <= 10){
arr[i][j]= false;
} else{
arr[i][j]= true;
}
}
}
}
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {
cell: "?",
style: "rgba(61, 130, 139, 0.11)"
};
}
handleChange = () => {
this.props.Explosion();
}
handleClick() {
const mine = <img alt="BOOM!" src={Mine}/>;
if(this.props.children ){
this.handleChange();
this.setState({cell: ""})
} else{
this.setState({cell: mine, style:"red"})
}
}
render() {
return (
<button style={{background: this.state.style}} className="square" onClick={() => this.handleClick()}>
{this.state.cell}
</button>
);
}
}
class Field extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: [],
field: true
};
Fill(this.state.arr)
}
Explosion = () => {
this.setState({field: false });
console.log(1);
};
Rows(arr,i){
return (
<div className="board-row" key={`${i}`} >
{arr}
</div>
)
}
render() {
for( var i = 0; i < N; i++){
for( var j = 0; j < N; j++){
this.state.arr[i][j] = <Square key={`${i} ${j}`} Explosion={this.Explosion} >
{this.state.arr[i][j]}</Square >
}
this.state.arr[i] = this.Rows( this.state.arr[i],i);
}
if (this.state.field){
return (
<div className="status">
{this.state.arr}
</div>
);
} else{
return(
<h1>You lose</h1>
);
}
}
}
ReactDOM.render(
<Field/>,
document.getElementById('root')
);
Ответы (1 шт):
Автор решения: xydope
→ Ссылка
У вас контекст теряется при передаче ф-ии потомку. См. пример, как контекст биндить
this.Explosion.bind(this)
class Field extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: [],
field: true
};
Fill(this.state.arr)
this.Explosion = this.Explosion.bind(this) //биндим контекст, методы, кстати, принято с маленькой буквы называть
}
Explosion = () => {
this.setState({field: false });
console.log(1);
};
//Ваш код
}