Reactjs 为什么此子组件属性值未定义?

Reactjs 为什么此子组件属性值未定义?,reactjs,react-component,react-state,Reactjs,React Component,React State,我正在学习ReactJS,并尝试使用react组件创建一个简单的测验。我有三个部分: FinalDiv——父组件 问题:显示问题 回答:显示该问题的选项 两者都是FinalDiv的子组件 为了计算正确答案和错误答案,并转到下一个问题,我使用的是MethodProcessor 我的问题是,我无法从答案组件中获取所选选项的值。选项的值存储在答案的capvalue属性中 到目前为止,我已经尝试了event.target.value在processor方法中访问该值。但在控制台中打印时,它会给出未定

我正在学习ReactJS,并尝试使用react组件创建一个简单的测验。我有三个部分:

FinalDiv——父组件

  • 问题:显示问题
  • 回答:显示该问题的选项
两者都是FinalDiv的子组件

为了计算正确答案和错误答案,并转到下一个问题,我使用的是MethodProcessor

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

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

我也试过这个。capvalue。但同样的结果

请注意,在渲染之前打印时,它给出的是正确的值,但在处理器方法中打印时,它给出的是未定义的值,因此我无法检查所选答案是否正确。请参见代码中的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();
import React,{Component}来自'React';
从“react dom”导入react dom;
导入“./index.css”;
将*作为serviceWorker从“/serviceWorker”导入;
常量questionBoxStyle={
背景颜色:“青色”,
textAlign:'中心',
宽度:“30%”,
高度:'50px',
保证金金额:35%,
marginTop:'50px',
marginBottom:'50px'
}
常量btnBoxStyle={
背景颜色:“橙色”,
textAlign:'中心',
宽度:“30%”,
高度:'50px',
保证金金额:35%,
}
类问题扩展组件{
render(){
返回(
{this.props.country}的首都是什么?
)
}
}
类答案扩展组件{
render(){
返回(
{this.props.capvalue}
)
}
}
类FinalDiv扩展了组件{
建造师(道具){
超级(道具);
此.state={
oq:[
{
问:“印度”,
作品:[“德里”、“孟买”、“加尔各答”、“钦奈”],
正确:“德里”
},
{
问:“美国”,
作品:[“华盛顿”、“纽约”、“芝加哥”、“洛杉矶”],
正确:“DC”
},
{
问:“英国”,
作品:[《普利茅斯》,《伦敦》,《曼彻斯特》,《德比》,
正确:“伦敦”
},
{
问:“德国”,
作品:[“多特蒙德”、“法兰克福”、“柏林”、“慕尼黑”],
正确:“柏林”
}
],
正确:0,
错误:0,
索引:0
}
this.processor=this.processor.bind(this);
}
处理器(事件){
//在下面的行中打印未定义的内容
console.log('selected:'+event.target.capvalue+'--实际答案:'+this.state.oq[this.state.currendex]。正确)
if(this.capvalue===this.state.oq[this.state.currendex]。正确){
这是我的国家({
更正:此。状态。更正+1,
})
}否则{
这是我的国家({
不正确:此。状态。不正确+1,
})
}
if(this.state.currendex==3){
这是我的国家({
索引:0
})
}否则{
这是我的国家({
currendex:this.state.currendex+1
})
}
}
render(){
返回(
{
this.state.oq[this.state.currendex].op.map((值,索引)
=> {
//如果我尝试在这里打印值,它会正确打印
console.log('当前索引:'+this.state.currendex+
'--correct:'+this.state.correct+'--correct:'+this.state.correct)
返回
})
}
对的:
{this.state.correct}
不正确:
{this.state.error}
)
}
}
ReactDOM.render(,document.getElementById('root'));
serviceWorker.unregister();
我的猜测是处理器方法无法访问父组件(FinalDiv)中的应答组件的属性。所以需要在子组件本身(应答组件)中做一些事情,但我不知道是什么。我是否以某种方式将状态传递给子组件或其他东西

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


我最近被解除了提问的障碍。

您需要从
答案
组件传递正确答案

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

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

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

事件目标是应答组件中的H3标记,它没有属性capvalue,因此,请尝试读取

event.target.capvalue

返回未定义的。你只需要改变一下

event.target.capvalue

event.target.innerHTML


代码将按预期工作。但是,这不是实现这一点的最佳方法,因此您应该采用不同的方法。我脑子里想的一个方法是为答案分配唯一的id,并将正确答案的id作为道具传递给答案。

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

event.target.capvalue

返回未定义的。你只需要改变一下

event.target.capvalue

event.target.innerHTML

代码将按预期工作。然而,这并不是实现这一点的最佳方法,所以你应该采用另一种方法。我脑子里最想做的一件事就是为答案分配唯一的id,并将正确答案的id作为道具传递给答案