Created
February 8, 2018 02:47
-
-
Save YKalashnikov/d87abfd5989006ac57531c363b3fea33 to your computer and use it in GitHub Desktop.
Having problem with a state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Box extends React.Component{ | |
constructor(props){ | |
super(props) | |
var c = [] | |
for(var i=0; i<100; i++){ | |
c.push( <Cell key={i} id={i} cells={c} /> ) | |
} | |
this.state={cells:c} | |
} | |
render(){ | |
return(<div> | |
{this.state.cells}</div>) | |
} | |
} | |
var events = {} | |
class Cell extends React.Component{ | |
constructor(props){ | |
super(props) | |
this.state={selected : false, nextState : false}; | |
} | |
isSelected(r,c){ | |
var size = Math.sqrt(this.props.cells.length) | |
if(r == -1) r = size - 1 | |
if(r == size) r = 0 | |
if(c == -1) c = size - 1 | |
if(c == size) c = 0 | |
var id = r * size + c | |
return this.props.cells[id].state.selected | |
} | |
calculate(){ | |
var neighbours = 0 | |
var size = Math.sqrt(this.props.cells.length) | |
var row = Math.floor( this.props.id / size ) | |
var col = this.props.id - row * size | |
if( this.isSelected( row - 1, col ) ) neighbours += 1 | |
if( this.isSelected( row - 1, col + 1 ) ) neighbours += 1 | |
if( this.isSelected( row - 1, col - 1 ) ) neighbours += 1 | |
if( this.isSelected( row, col + 1 ) ) neighbours += 1 | |
if( this.isSelected( row, col - 1 ) ) neighbours += 1 | |
if( this.isSelected( row + 1, col ) ) neighbours += 1 | |
if( this.isSelected( row + 1, col + 1 ) ) neighbours += 1 | |
if( this.isSelected( row + 1, col - 1 ) ) neighbours += 1 | |
this.state.nextState = false | |
if( this.state.selected ){ | |
if( neighbours < 2) this.state.nextState = false | |
if( neighbours > 3) this.state.nextState = false | |
if( neighbours == 3 || neighbours == 2) this.state.nextState = true | |
}else{ | |
if( neighbours == 3) this.state.nextState = true | |
} | |
} | |
onClick(e){ | |
this.setState({selected: !this.state.selected}); | |
console.log("e") | |
} | |
componentDidMount(){ | |
this.props.cells[this.props.id] = this | |
$(events).on("calculate", this.calculate) | |
$(events).on("renderNext", this.renderNext) | |
} | |
renderNext(){ | |
this.setState({selected: this.state.nextState}) | |
} | |
render(){ | |
return( | |
<div className={this.state.selected?"cell active":"cell"} | |
onClick={this.onClick} > | |
</div> | |
) | |
} | |
} | |
$(document).keydown=((e)=>{ | |
if (e.which === 32){ //enter | |
$(events).trigger('calculate') | |
$(events).trigger('renderNext') | |
} | |
}) | |
ReactDOM.render( | |
<Box/>, | |
document.getElementById('app')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment