如何比较React中2个组件的状态变量?

时间:2019-01-12 09:51:11

标签: reactjs jsx

我有一个组件,其状态有一个存储0-3随机值的变量,我的app.js中有2个组件,现在我想比较这2个组件的状态。请帮忙。

这是我的组件。

import React from "react";

export default class player extends React.Component {
constructor(...args) {
super(...args);
this.state = {
  shoot: 0
};
}
shooter = () => {
this.setState({ shoot: Math.floor(Math.random() * Math.floor(3)) });
}

render() {
return (
  <div>
    <h1>{this.state.shoot}</h1>
    <button onClick={() => this.shooter()}>shoot it</button>
  </div>
);
}
}

这是我的app.js

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import Player from "./player";

class App extends Component {
render() {
return (
  <div className="App">
    <div>
      <Player />
      <Player />
    </div>
  </div>
);
}
}

export default App;

如何比较两个state.shoot中的<Player />?我想检查两个state.shoot是否相等。

1 个答案:

答案 0 :(得分:1)

我建议将状态放入应用程序组件中。这样,您就可以对数据进行更多处理,例如:

应用程序组件:

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import Player from "./player";

class App extends Component {
    constructor(...args) {
super(...aan rgs);
this.state = {
    // create array of all your players
        players : [{shoot :0}, {shoot :0}]
    }
}
shooter = (id) => {
let players = this.state.player
/// maping the new players array
players.map(element, index => {
    if(id == index){
        element.shoot = Math.floor(Math.random() * Math.floor(3)
    }
}
this.setState({players) });
}

checkPlayers = () =>{
    // this is example... you can loop over your array and find what you need
    if(this.state.players[0].shoot == this.state.players[1].shoot){
        return true
    }
    else{
        return false
    }
}

render() {
return (
  <div className="App">
    <div>
    {this.state.players.map(i => {
        // pass the values to the player component (don't forget the id)
        return <Player shoot={i.shoot} shooter={this.shooter} id={i}/>
    }
    </div>
  </div>
);
}
}

export default App;

播放器组件:

import React from "react";

export default class player extends React.Component {

setShooter = () => {
    this.props.shooter(this.props.id)
}

render() {
return (
  <div>
    <h1>{this.props.shoot}</h1>
    <button onClick={this.setShooter}</button>
  </div>
);
}
}

export default player;