反应孩子与父母的沟通问题

我正在构建一个猜谜游戏,其中问题和选择逻辑位于名为 Questions 的组件中.我无法让 App 读取问题代码.我希望 App 中的状态根据子组件中的选择进行更新.

我一直在尝试从 如何在 ReactJS 中将数据从子组件传递到其父组件? 和 https://malithjayaweera.com/2018/01/reactjs-passing-data-react-components/,但我不清楚如何将它应用到我的项目中.

应用程序:

import React, { Component } from 'react';导入'./App.css';从./Timer"导入定时器;从./Questions/Questions.js"导入问题;从../src/Results"导入结果;类应用扩展组件{状态 = {总真:0,完全错误:0,}组件DidMount() {console.log(`TotalTrue: ${this.state.totalTrue}`);console.log(`TotalFalse: ${this.state.totalFalse}`);}//提交按钮处理表单提交 = 事件 =>{event.preventDefault();console.log("点击提交按钮");};callbackHandlerFunction = (selectedOption) =>{this.setState({ selectedOption });}使成为() {返回 (<div className="视差"><div className="App"><div className="包装器"><div className="headerDiv"><h1>皮克斯琐事!</h1></div><div className="timerDiv"><定时器/></div><div className="questionSection"><问题handleClickInParent={this.callbackHandlerFunction}/></div>

<button onClick={this.handleFormSubmit}>提交</button></div>{/* this.state.articles.length >0&&...*/}<div className="resultsDiv"><结果totalTrue={this.state.totalTrue}totalFalse={this.state.totalFalse}/></div></div></div></div>);}}导出默认应用程序;

问题:

import React, { Component } from "react";从反应选择"中导入选择;导入./Questions.css";常量 answerChoices = [{编号:1,text: "1. 背景图片是《玩具总动员》中席德家的地毯.是什么电影启发了它?",答案:[{标签:2001:太空漫游",值:假},{标签:闪灵",值:真},{标签:一只飞过杜鹃巢",值:假},{标签:教父",值:假}]},---- 完整的问题削减了空间.我正在使用 https://github.com/JedWatson/react-select 并且该功能有效.----{编号:8,text: "8. 谁是《海底总动员》中马林的原声?",答案:[{标签:阿尔伯特布鲁克斯",值:假},{标签:丹尼斯·利里",值:假},{标签:布拉德·加勒特",值:假},{标签:威廉·H·梅西",值:真}]}];类问题扩展组件{状态 = {答案选择,选定选项:空,}handleChange = (selectedOption) =>{this.setState({ selectedOption });console.log(`Option selected:`, selectedOption);常量 answerValue = selectedOption.value;if (answerValue === true) {//console.log(answerValue);this.setState({totalTrue: this.totalTrue + 1}, () => {console.log(`New TotalTrue: ${this.totalTrue}`);});};if (answerValue === false) {//console.log(answerValue);this.setState({totalFalse: this.totalFalse + 1}, () => {console.log(`新的 TotalFalse: ${this.totalFalse}`);});};this.props.handleClickInParent({selectedOption});}使成为() {//const { selectedOption } = this.state;返回 (<div className="questionsDiv"><ol>{this.state.answerChoices.map(问题 => {返回 (<div className="individualQuestions" key={question.id}>{问题.文本}<选择值={this.selectedOption}onChange={this.handleChange}选项={question.answers}/></div>)})}</ol></div>)}}导出默认问题;

解决方案

我做了一些更改,现在可以使用了.

代码现在看起来像这样.

callbackHandlerFunction = ( selectedOption ) =>{常量 answerValue = selectedOption.value;if (answerValue === true) {//console.log(answerValue);this.setState({totalTrue: this.state.totalTrue + 1}, () => {console.log(`New TotalTrue: ${this.state.totalTrue}`);});};if (answerValue === false) {//console.log(answerValue);this.setState({totalFalse: this.state.totalFalse + 1}, () => {console.log(`New TotalFalse: ${this.state.totalFalse}`);});};}

handleChange = (selectedOption) =>{this.props.handleClickInParent(selectedOption);}

I'm building a guessing game, where the questions and selection logic is in a component called Questions. I'm having trouble getting App to read the Questions code. I want the state in App to update based on selections in the child component.

I've been trying to reverse engineer a solution from How to pass data from child component to its parent in ReactJS? and https://malithjayaweera.com/2018/01/reactjs-passing-data-react-components/, but I'm not clear on how to apply it to my project.

App:

import React, { Component } from 'react';
import './App.css';
import Timer from "./Timer";
import Questions from "./Questions/Questions.js";
import Results from "../src/Results";

class App extends Component {

  state = {
    totalTrue: 0,
    totalFalse: 0,
  }

  componentDidMount() {
    console.log(`TotalTrue: ${this.state.totalTrue}`);
    console.log(`TotalFalse: ${this.state.totalFalse}`);
  }

  // submit button
  handleFormSubmit = event => {
    event.preventDefault();
    console.log("submit button clicked");
  };

  callbackHandlerFunction = (selectedOption) => {
    this.setState({ selectedOption });
  }

  render() {
    return (

      <div className="parallax">

      <div className="App">

      <div className="wrapper">

      <div className="headerDiv">
      <h1>Pixar Trivia!</h1>
    </div>

    <div className="timerDiv">
      <Timer />
      </div>

      <div className="questionSection">
      <Questions
    handleClickInParent={this.callbackHandlerFunction}
    />
    </div>

    <div>
    <button onClick={this.handleFormSubmit}>Submit</button>
      </div>

    {/* this.state.articles.length > 0 && ...*/}
  <div className="resultsDiv">
      <Results
    totalTrue={this.state.totalTrue}
    totalFalse={this.state.totalFalse}
    />
    </div>

    </div>

    </div>

    </div>
  );
  }
}

export default App;

Questions:

import React, { Component } from "react";
import Select from "react-select";
import "./Questions.css";

const answerChoices = [
    {
        id: 1,
        text: "1. The background image is the carpet from Sid's house in Toy Story. What movie inspired it?",
        answers: [
        {
            label: "2001: A Space Odyssey",
            value: false
        },
        {
            label: "The Shining",
            value: true
        },
        {
            label: "One Flew Over the Cuckoo's Nest",
            value: false
        },
        {
            label: "The Godfather",
            value: false
        }
        ]
},
  ---- full questions cut for space. I'm using https://github.com/JedWatson/react-select and the functionality works. ----
{
    id: 8,
    text: "8. Who was the original voice of Marlin from "Finding Nemo"?",
    answers: [
        {
            label: "Albert Brooks",
            value: false
        },
        { 
            label: "Denis Leary",
            value: false
        },
        {
            label: "Brad Garrett",
            value: false
        },
        {
            label: "William H. Macy",
            value: true
        }
        ]
    }
];

class Questions extends Component {

state = {
    answerChoices,
    selectedOption: null,
}

handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);

    const answerValue = selectedOption.value;
    if (answerValue === true) {
        // console.log(answerValue);
        this.setState({totalTrue: this.totalTrue + 1}, () => {
            console.log(`New TotalTrue: ${this.totalTrue}`);
        });
    };
    if (answerValue === false) {
        // console.log(answerValue);
        this.setState({totalFalse: this.totalFalse + 1}, () => {
            console.log(`New TotalFalse: ${this.totalFalse}`);
        });
    };
    this.props.handleClickInParent({selectedOption});

  }

render() {
    // const { selectedOption } = this.state;

    return (

        <div className="questionsDiv">

            <ol>
                {this.state.answerChoices.map(question => {
                return (

                    <div className="individualQuestions" key={question.id}>

                        {question.text}

                        <Select
                            value={this.selectedOption}
                            onChange={this.handleChange}
                            options={question.answers}
                        />

                    </div>

                    )  
                })}
            </ol>

        </div>

    )
  }

}

export default Questions;

解决方案

I made some changes and it is working now.

The code looks like this now.

callbackHandlerFunction = ( selectedOption ) => {
  const answerValue = selectedOption.value;
  if (answerValue === true) {
      // console.log(answerValue);
      this.setState({totalTrue: this.state.totalTrue + 1}, () => {
          console.log(`New TotalTrue: ${this.state.totalTrue}`);
      });
  };
  if (answerValue === false) {
      // console.log(answerValue);
      this.setState({totalFalse: this.state.totalFalse + 1}, () => {
          console.log(`New TotalFalse: ${this.state.totalFalse}`);
      });
  };
}  

and

handleChange = (selectedOption) => {

    this.props.handleClickInParent(selectedOption);
  }

相关文章