Reactjs 在react js的父类中单击按钮时,将布尔状态值从父类传递给子类,这样我就可以用布尔加载测验

Reactjs 在react js的父类中单击按钮时,将布尔状态值从父类传递给子类,这样我就可以用布尔加载测验,reactjs,Reactjs,家长班欢迎 在这里,我点击了一个名为Rookie的按钮,它会触发该级别的状态值,我想将该val发送给Quike类,以便我可以使用它来显示Quikes。我不知道我现在所做的是否正确 class Welcome extends Component { constructor(props) { super(props); this.state = { viewquiz: false, people: [], dataHasLoaded: fals

家长班欢迎

在这里,我点击了一个名为Rookie的按钮,它会触发该级别的状态值,我想将该val发送给Quike类,以便我可以使用它来显示Quikes。我不知道我现在所做的是否正确

class Welcome extends Component {
  constructor(props) {
    super(props);
    this.state = {
      viewquiz: false,
      people: [],
      dataHasLoaded: false,
      user: {},
      viewProfile: false

      // viewLogin:false
    };
    this.changeToquiz1 = this.changeToquiz1.bind(this);
  }
  changeToquiz1 = () => {
    this.setState({
      level1: true,
      level2: false,
      level3: false,
      level4: false,
      level5: false
    });
  };

  changeToquiz2 = () => {
    this.setState({
      level1: false,
      level2: true,
      level3: false,
      level4: false,
      level5: false
    });
    console.log("quiz2 clciked");
  };

  changeToquiz3 = () => {
    this.setState({
      level1: false,
      level2: false,
      level3: true,
      level4: false,
      level5: false
    });
  };
  changeToquiz4 = () => {
    this.setState({
      level1: false,
      level2: false,
      level3: false,
      level4: true,
      level5: false
    });
  };
  changeToquiz5 = () => {
    this.setState({
      level1: false,
      level2: false,
      level3: false,
      level4: false,
      level5: true
    });
  };

  componentDidMount() {
    this.authListener();
    this.retrieveData();
    console.log("Data loaded");
  }

  authListener = () => {
    //checks if user is already logged in 0n browser
    fire.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({
          user
        });
      } else {
        this.setState({ user: null });
      }
      return user;
    });
  };
  retrieveData = () => {
    fire.auth().onAuthStateChanged(user => {
      if (user) {
        var ref = fire
          .database()
          .ref("data")
          .limitToLast(1);
        //takes the last data in DB

        var userUID = fire.auth().currentUser.uid;
        var query = ref.orderByChild("ID").equalTo(userUID); //retrieves data about only the current logged in user
        console.log(userUID);
        query.once("value", snapshot => {
          let currentState = this.state.people;

          const currentUser = snapshot.val();
          for (let i in currentUser) {
            currentState.push({
              email: currentUser[i].UserEmail,
              UserAnswer: currentUser[i].UserAnswer,
              Questions: currentUser[i].Question,
              id: currentUser[i].ID,
              Score: currentUser[i].Score,
              Level: currentUser[i].userLevel
            });
          }
          // currentState.push(user);
          console.log(currentState);

          this.setState({
            people: currentState,
            dataHasLoaded: true
          });
        });
      } else {
        console.log("no user");
      }
    });
  };

  changetoQuiz = () => {
    this.setState({
      viewquiz: true
    });
  };
  changetoProfile = () => {
    this.setState({
      viewProfile: !this.state.viewProfile
    });
  };

  logout = e => {
    e.preventDefault();
    fire.auth().signOut();
    console.log("Logged out");
  };

  render() {
    const x = this.props.stateQuiz1;

    let renderData = this.state.people.map((person, index) => {
      return (
        <div style={{ color: " black" }} key={index}>
          {this.state.viewProfile ? (
            <UserProfile
              className="userProfile"
              level={person.UserLevel}
              score={person.Score}
              question={person.Questions}
              email={person.email}
            />
          ) : null}
        </div>
      );
    });

    let loadingSpinner = <Loader id="loader" type="ThreeDots" color="red " />;

    return (
      <div>
        <div>
          <Navbar id="navbar" bg="primary" variant="dark">
            <Nav className="mr-auto" style={{ fontSize: 25 }}>
              Welcome
              <ButtonToolbar>
                <Button onClick={this.changeToquiz1}>Rookie</Button>
                <Button onClick={this.changeToquiz2}>Student</Button>
                <Button>Intermediate</Button>
                <Button>Expert</Button>
                <Button>Master</Button>
              </ButtonToolbar>
            </Nav>
            <Button onClick={this.logout}>
              <Nav>
                Logout <FiLogOut />
              </Nav>
            </Button>
            <Button onClick={this.changetoProfile}>
              <Nav>
                Profile <MdPerson />
              </Nav>
            </Button>
          </Navbar>

          <Test stateOutput={this.changeToquiz1} />
        </div>

        <div style={{ backgroundColor: "white" }}>
          <h3 className="heading" style={{ color: "black" }}>
            Guarding <GiSwordsEmblem />
          </h3>
          <p className="groove">
            Fixed guards must always be kept in place. These prevent
            entanglement The guard should ensure that no part of your body can
            reach the danger zone Fixed guarding of older machines should be
            upgraded in line with the guarding on newer models Do not use a
            machine unless all guards are in place
          </p>

          <h3 className="heading" style={{ color: "black" }}>
            Machinery Checks <MdCheckBox />
            <p className="groove">
              All safety guards/ devices fitted The PTO "O" guards present
              Hydraulic systems and hoses in good repair All machinery defects
              identified and corrected Regular maintenance carried out
            </p>
          </h3>

          <h3 className="heading" style={{ color: "black" }}>
            Machinery Checks <MdCheckBox />
            <p className="groove">
              All safety guards/ devices fitted The PTO "O" guards present
              Hydraulic systems and hoses in good repair All machinery defects
              identified and corrected Regular maintenance carried out
            </p>
          </h3>
          <h3 className="heading" style={{ color: "black" }}>
            Machinery Fatalities <MdCheckBox />
            <p className="groove">
              Tractors and Machinery are the main cause of farm accidents in
              Ireland. Elderly farmers and children are at particular risk.
              Being entangled in PTO’s, crushed under a machine part, caught in
              a machine mechanism, crushed between vehicles and struck by a
              machine object are the main causes of deaths with farm machinery.
              <img src={piechart} alt="" />
            </p>
          </h3>
          {<div>{this.state.dataHasLoaded ? renderData : loadingSpinner}</div>}
          <Button onClick={this.changetoQuiz}>Take the Quiz</Button>

          {this.state.viewquiz ? (
            <Quiz stateOutput={this.changeToquiz1} />
          ) : null}
        </div>
      </div>
    );
  }
}
export default Welcome;
类欢迎扩展组件{
建造师(道具){
超级(道具);
此.state={
viewquick:false,
人员:[],
dataHasLoaded:false,
用户:{},
视图配置文件:false
//viewLogin:false
};
this.changeToquiz1=this.changeToquiz1.bind(this);
}
changeToquiz1=()=>{
这是我的国家({
级别1:正确,
第二级:错误,
第三级:错误,
第四级:错误,
第五级:错误
});
};
changeToquiz2=()=>{
这是我的国家({
第1级:错误,
第二级:正确,
第三级:错误,
第四级:错误,
第五级:错误
});
控制台日志(“quiz2 clciked”);
};
changeToquiz3=()=>{
这是我的国家({
第1级:错误,
第二级:错误,
第三级:正确,
第四级:错误,
第五级:错误
});
};
changeToquiz4=()=>{
这是我的国家({
第1级:错误,
第二级:错误,
第三级:错误,
第四级:正确,
第五级:错误
});
};
changeToquiz5=()=>{
这是我的国家({
第1级:错误,
第二级:错误,
第三级:错误,
第四级:错误,
第五级:正确
});
};
componentDidMount(){
this.authListener();
这个。retrieveData();
控制台日志(“数据加载”);
}
authListener=()=>{
//检查用户是否已登录到0n浏览器
fire.auth().onAuthStateChanged(用户=>{
如果(用户){
这是我的国家({
用户
});
}否则{
this.setState({user:null});
}
返回用户;
});
};
检索数据=()=>{
fire.auth().onAuthStateChanged(用户=>{
如果(用户){
var ref=火灾
.数据库()
.ref(“数据”)
.limitToLast(1);
//获取数据库中的最后一个数据
var userUID=fire.auth().currentUser.uid;
var query=ref.orderByChild(“ID”).equalTo(userUID);//仅检索有关当前登录用户的数据
日志(userUID);
query.once(“值”,快照=>{
让currentState=this.state.people;
const currentUser=snapshot.val();
for(让我输入currentUser){
当前状态推送({
电子邮件:currentUser[i]。UserEmail,
UserAnswer:currentUser[i]。UserAnswer,
问题:当前用户[i]。问题,
id:currentUser[i]。id,
分数:当前用户[i]。分数,
级别:currentUser[i]。userLevel
});
}
//currentState.push(用户);
console.log(当前状态);
这是我的国家({
人民:现状,,
dataHasLoaded:true
});
});
}否则{
console.log(“无用户”);
}
});
};
changetoquick=()=>{
这是我的国家({
VIEWQUICK:对
});
};
changetoProfile=()=>{
这是我的国家({
viewProfile:!this.state.viewProfile
});
};
注销=e=>{
e、 预防默认值();
fire.auth().signOut();
控制台日志(“注销”);
};
render(){
const x=this.props.stateQuiz1;
让renderData=this.state.people.map((person,index)=>{
返回(
{this.state.viewProfile(
):null}
);
});
设loadingSpinner=;
返回(
欢迎
菜鸟
学生
中间的
专家
主人
注销
轮廓
守卫

固定防护装置必须始终保持在适当的位置。这些装置可防止 护卫应该确保你身体的任何部位都不能 到达危险区域时,应安装旧机器的固定防护装置 更新型号上的防护升级不使用 除非所有防护装置均已就位,否则不得使用机器

机械检查

安装PTO“O”防护装置的所有安全防护装置/装置均存在 液压系统和软管状况良好,可修复所有机械缺陷 确定并纠正定期维护

机械检查

安装PTO“O”防护装置的所有安全防护装置/装置均存在 液压系统和软管状况良好,可修复所有机械缺陷 确定并纠正定期维护

机械死亡

拖拉机和机械是中国农业事故的主要原因 老年农民和儿童尤其危险。 被PTO缠住,压碎在机器部件下,卡在 一种机械装置,在车辆之间被压碎并被撞击 机器物体是导致农业机械死亡的主要原因。

{{this.state.datahasload?renderData:loadingSpinner} 参加测验 {this.state.viewquick( ):null} ); } } 出口默认值欢迎;
儿童班测验 我在这里
class Quiz extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userAns: null,
      options: [],
      disabled: false,
      currentQuest: 0,
      isEnd: false,
      scores: 0,
      pictures: "",
      level1: false,
      level2: false,
      level3: false,
      level4: false,
      level5: false
    };
    //  this.changeToquiz2 = this.changeToquiz2.bind();
  }
  loadQuiz = () => {
    const { currentQuest } = this.state;
    //  console.log(Quizdata[2].question);
    this.setState(() => {
      return {
        questions: Quizdata[currentQuest].question,
        options: Quizdata[currentQuest].options,
        answer: Quizdata[currentQuest].answer,
        pictures: Quizdata[currentQuest].picture
      };
    });
    console.log(this.state.answer);
  };
  loadQuiz2 = () => {
    const { currentQuest } = this.state;
    //  console.log(Quizdata[2].question);
    this.setState(() => {
      return {
        questions: Quizdata2[currentQuest].question,
        options: Quizdata2[currentQuest].options,
        answer: Quizdata2[currentQuest].answer,
        pictures: Quizdata2[currentQuest].picture
      };
    });
    console.log(this.state.answer);
  };
  loadQuiz3 = () => {
    const { currentQuest } = this.state;
    //  console.log(Quizdata[2].question);
    this.setState(() => {
      return {
        questions: Quizdata3[currentQuest].question,
        options: Quizdata3[currentQuest].options,
        answer: Quizdata3[currentQuest].answer,
        pictures: Quizdata3[currentQuest].picture
      };
    });
    console.log(this.state.answer);
  };
  false;
  loadQuiz4 = () => {
    const { currentQuest } = this.state;
    //  console.log(Quizdata[2].question);
    this.setState(() => {
      return {
        questions: Quizdata4[currentQuest].question,
        options: Quizdata4[currentQuest].options,
        answer: Quizdata4[currentQuest].answer,
        pictures: Quizdata4[currentQuest].picture
      };
    });
    console.log(this.state.answer);
  };
  loadQuiz5 = () => {
    const { currentQuest } = this.state;
    //  console.log(Quizdata[2].question);
    this.setState(() => {
      return {
        questions: Quizdata5[currentQuest].question,
        options: Quizdata5[currentQuest].options,
        answer: Quizdata5[currentQuest].answer,
        pictures: Quizdata5[currentQuest].picture
      };
    });
    console.log(this.state.answer);
  };

  changeToquiz1 = () => {
    this.setState({
      level1: true,
      level2: false,
      level3: false,
      level4: false,
      level5: false
    });
  };

  changeToquiz2 = () => {
    this.setState({
      level1: false,
      level2: true,
      level3: false,
      level4: false,
      level5: false
    });
  };
  changeToquiz3 = () => {
    this.setState({
      level1: false,
      level2: false,
      level3: true,
      level4: false,
      level5: false
    });
  };
  changeToquiz4 = () => {
    this.setState({
      level1: false,
      level2: false,
      level3: false,
      level4: true,
      level5: false
    });
  };
  changeToquiz5 = () => {
    this.setState({
      level1: false,
      level2: false,
      level3: false,
      level4: false,
      level5: true
    });
  };

  nextQuestion = e => {
    // e.preventDefault();
    if (this.state.userAns === null) {
      alert("choose an option");
      return;
    }
    this.setState({
      currentQuest: this.state.currentQuest + 1
    });
    this.setState({
      userAns: null
    });
    // console.log(this.state.currentQuest);
  };

  checkAns = userAns => {
    const { answer, scores } = this.state;

    this.setState({
      userAns: answer,
      disabled: false
    });
    console.log(userAns);
    if (userAns === answer) {
      console.log("Correct");
      this.setState({
        scores: scores + 1
      });
    } else {
      console.log("Wrong");
      alert("Correct answer is " + answer);
    }
  };

  componentDidMount() {
    if (this.state.level1) {
      this.loadQuiz();
      console.log("Quiz1 loaded"); //loads quiz  data in
    }
    if (this.state.level2) {
      this.loadQuiz2(); //loads quiz  data in
      console.log("Quiz2 loaded");
    }
    if (this.state.level3) {
      this.loadQuiz3(); //loads quiz  data i
      console.log("Quiz3 loaded");
    }
    if (this.state.level4) {
      this.loadQuiz4(); //changeToquiz2 quiz  data in
      console.log("Quiz4 loaded");
    }
    if (this.state.level5) {
      this.loadQuiz5(); //loads quiz  data in
      console.log("Quiz5 loaded");
    } else {
      console.log("No user states changed");
    }
  }

  componentDidUpdate(prevProps, prevState) {
    const { currentQuest } = this.state;
    if (this.state.currentQuest !== prevState.currentQuest) {
      this.setState({
        disabled: true,
        questions: Quizdata[currentQuest].question,
        options: Quizdata[currentQuest].options,
        answer: Quizdata[currentQuest].answer,
        pictures: Quizdata[currentQuest].picture
      });
    }
  }

  logout = e => {
    e.preventDefault();
    fire.auth().signOut();
    console.log("Logged out");
  };

  pushtoDB = () => {
    var ref = fire.database().ref("data");
    var newRef = ref.push();
    newRef.set({
      ID: fire.auth().currentUser.uid,
      UserEmail: fire.auth().currentUser.email,
      Question: this.state.questions, //Send data to DB to track for analysis
      UserAnswer: this.state.userAns,
      Score: this.state.scores,
      userLevel: this.state.level1
    });

    console.log("Sent to Database");
  };

  pushtoDB2 = () => {
    var ref = fire.database().ref("data");
    var newRef = ref.push();
    newRef.set({
      ID: fire.auth().currentUser.uid,
      UserEmail: fire.auth().currentUser.email,
      Question: this.state.questions, //Send data to DB to track for analysis
      UserAnswer: this.state.userAns,
      Score: this.state.scores,
      userLevel: this.state.level1
    });
    console.log("Sent to Database");
  };

  finishQuiz = () => {
    if (this.state.currentQuestion === Quizdata.length - 1) {
      this.setState({
        isEnd: true
      });
      return (
        <h3>
          Quiz Finished, You scored {this.state.scores}/{Quizdata.length - 1}!
        </h3>
      );
    }
  };

  render() {
    const { userAns, options, currentQuest, isEnd } = this.state;
    if (isEnd) {
      return (
        <div>
          <Alert>Quiz Finished</Alert>
          <span>
            Quiz score : {this.state.scores}/{Quizdata.length - 1}
          </span>
        </div>
      );
    } else {
      return (
        <div className="quizForm">
          <br></br>
          {/*  <Welcome stateQuiz1={this.changeToquiz2} />*/}

          <div>
            <ProgressBar animated now={this.state.currentQuest * 10} />
          </div>
          {this.state.questions}
          <br></br>
          <p>Q{this.state.currentQuest}</p>

          {this.state.pictures}
          <br></br>
          {options.map(option => (
            <Button
              size="lg"
              block
              key={option.id}
              className={`ui floating message options
            ${userAns === option ? "selected" : null}
           `}
              onClick={() => this.checkAns(option)}
            >
              {option}
            </Button>
          ))}

          <br></br>
          <Button onClick={() => this.checkAns()}>
            CHECK <FaHorse />
          </Button>
          {currentQuest < Quizdata.length - 1 && (
            <Button
              disabled={this.state.disabled}
              onClick={() => {
                this.nextQuestion();
                this.pushtoDB();
              }}
            >
              NEXT <FaArrowRight />
            </Button>
          )}
          <br></br>

          {currentQuest === Quizdata.length - 1 && (
            <Button
              onClick={() => {
                this.pushtoDB2();
                this.finishQuiz();
                this.chooseLevel1();
              }}
            >
              Finish
            </Button>
          )}
        </div>
      );
    }
  }
}
export default Quiz;
<Quiz level1={this.state.level1} />