为什么此反应子组件属性值不确定



我正在学习reactjs,我正在尝试使用React组件创建一个简单的测验。我有三个组件:

finalDiv - 父级

  • 问题:显示问题
  • 答案:显示该问题的选项

两者都是 finalDiv

的子部分

用于计算正确和错误的答案,并转到下一个问题,我正在使用方法处理器

我的问题是,我无法从答案组件中获取所选选项的值。选项的值存储在 capvalue >答案的属性中。

到目前为止,我已经尝试了event.target.value以 processor 方法访问该值。但是它在控制台打印时给出了不确定的。

我也尝试过 this.capvalue 。但结果相同。

介意在渲染前打印时给出正确的值,但是在 processor 方法中打印时,它给出了 undefined 值,因为我无法检查如果选择的答案是正确的。请参阅代码中的2条评论:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
const questionBoxStyle = {
backgroundColor : 'cyan',
textAlign : 'center',
width : '30%',
height : '50px',
marginLeft : '35%',
marginTop : '50px',
marginBottom : '50px'
}
const btnBoxStyle = {
backgroundColor : 'orange',
textAlign : 'center',
width : '30%',
height : '50px',
marginLeft : '35%',
}
class Question extends Component {
render() {
    return(
        <div style={this.props.style}>
            What is the capital of {this.props.country} ?
        </div>
    )
}
}
class Answer extends Component {
render() {
    return(
        <button onClick={this.props.doOnClick} style={this.props.style}>
            <h3>{this.props.capvalue}</h3>
        </button>
    )
}
}
class FinalDiv extends Component {
constructor(props) {
    super(props);
        this.state = {
            oq : [
                {
                    q : 'India',
                    op : ['Delhi','Mumbai','Kolkata','Chennai'],
                    correct : 'Delhi'
                },
                {
                    q : 'USA',
                    op : ['DC','New York','Chicago','LA'],
                    correct : 'DC'
                },
                {
                    q : 'UK',
                    op : ['Plymouth','London','Manchester','Derby'],
                    correct : 'London'
                },
                {
                    q : 'Germany',
                    op : ['Dortmund','Frankfurt','Berlin','Munich'],
                    correct : 'Berlin'
                }
            ],
            correct : 0,
            incorrect : 0,
            currIndex : 0
        }
        this.processor = this.processor.bind(this);
}
processor(event) {
// prints undefined in below line
    console.log('selected: '+event.target.capvalue+' -- actual answer: '+this.state.oq[this.state.currIndex].correct)
    if(this.capvalue === this.state.oq[this.state.currIndex].correct) {
        this.setState({
            correct : this.state.correct+1,
        })
    } else {
        this.setState({
            incorrect : this.state.incorrect+1,
        })
    }
    if(this.state.currIndex === 3) {
        this.setState({
            currIndex : 0
        })
    } else {
        this.setState({
            currIndex : this.state.currIndex+1 
        })
    }
}
render() {
    return(
        <div>
            <Question style={questionBoxStyle} country= 
 {this.state.oq[this.state.currIndex].q}/>
            {
                this.state.oq[this.state.currIndex].op.map((value, index) 
=> {
// if i try to print the value here, it prints correctly
                console.log('current index: '+this.state.currIndex+
' -- correct: '+this.state.correct+' -- incorrect: '+this.state.incorrect)
                   return <Answer key={index} style={btnBoxStyle} 
capvalue={value} doOnClick={this.processor}/>
               })
            }
            <div style={questionBoxStyle}> <h2> Correct : 
{this.state.correct} </h2> </div>
            <div style={questionBoxStyle}> <h2> InCorrect : 
{this.state.incorrect} </h2> </div>
        </div>
    )
}
}
ReactDOM.render(<FinalDiv />, document.getElementById('root'));

serviceWorker.unregister();

我的猜测是,处理器方法无法访问父组件(finalDiv(中的 anders 组件的属性。因此,需要在儿童组件本身(答案组件(中做些事情,但我不知道。我是否以某种方式将状态传递给儿童组成部分?

如果您知道其他信息或问题格式是否错误,请告诉我。

我最近从提出问题中没有阻碍。

您需要从 Answer组件中传递正确的答案,

<button onClick={e => this.props.doOnClick(this.props.capvalue)} style={this.props.style}>
   <h3>{this.props.capvalue}</h3>
</button>

您的processor功能应该是

processor(capvalue) {
    console.log(
      'selected: ' +
        capvalue +
        ' -- actual answer: ' +
        this.state.oq[this.state.currIndex].correct,
    )
    if (capvalue === this.state.oq[this.state.currIndex].correct) {
      this.setState({
        correct: this.state.correct + 1,
      })
    } else {
      this.setState({
        incorrect: this.state.incorrect + 1,
      })
    }
    if (this.state.currIndex === 3) {
      this.setState({
        currIndex: 0,
      })
    } else {
      this.setState({
        currIndex: this.state.currIndex + 1,
      })
    }
  }

demo

事件目标是答案组件中的H3标签,因此没有属性capvalue,因此,尝试读取

event.target.capvalue

返回未定义。您只需要更改

event.target.capvalue

to

event.target.innerhtml

,代码将按预期工作。但是,这不是实现这一目标的最佳方法,因此您应该采用另一种方法。我的头顶上的一个是将独特的ID分配给答案并传递正确的答案ID作为Prop。

最新更新