将Q& A与React相匹配?

时间:2018-06-18 16:03:56

标签: javascript reactjs

我有一系列问题和一组答案。每个答案是一个问题的唯一正确答案。我需要在点击时突出显示正确的选定问题或答案。

例如:

  • 点击问题后,将该特定问题的课程更改为" active" (所以css改变了)
  • 点击答案后,将该特定答案的课程更改为"有效"

这是主要页面:

constructor(props) {
    super(props)
    this.handleQAClick = this.handleQAClick.bind(this)
    this.toggleColour = this.toggleColour.bind(this)

    this.state = {
        questions: [],
        active: true
    }
}

...

handleQAClick = (type, id) => {
    console.log(id)
    console.log(type)
    this.toggleColour(id)
}

toggleColour = id => {
    this.setState({active: !this.state.active})
    console.log('should change colour')
}

...

<Card>
    {this.state.questions.length 
        ? (
            <List>
                {this.state.questions.map(question => (
                    <ListItem key={question._id}>
                        <MatchItem
                            id={question._id}
                            type="question"
                            active={this.state.active}
                            text={question.question}
                            handleClick={this.handleQAClick}
                        />
                    </ListItem>
                ))}
            </List>
        )
        : ('No questions found')                        
    }
</Card>
<Card>
    {this.state.questions.length 
        ? (
            <List>
                {this.state.questions.map(question => (
                    <ListItem key={question._id}>
                        <MatchItem
                            id={question._id}
                            type="answer"
                            text={question.option1}
                            handleClick={this.handleQAClick}
                        />
                    </ListItem>
                ))}
            </List>
        )
        : ('No questions found')                        
    }
</Card>

这是MatchItem组件:

import React, {Component} from 'react'

export class MatchItem extends Component {
    render() {
        return (
            <div className={`match-item${this.props.active ? "-active" : ""}`} data-id={this.props.id} data-type={this.props.type} onClick={() => this.props.handleClick(this.props.id, this.props.type)}>
                {this.props.text}
            </div>
        )
    }
}

1 个答案:

答案 0 :(得分:1)

解决这个问题的一种方法是:

  • 为每张卡片分配唯一ID(问题)。
  • 以这种方式更改课程 <Component className={this.state.currQuestion === question.id ? 'active' : null} onClick={this.handleClick(question.id)} />

  • 您可以通过以下方式管理状态: handleClick = (id) => { this.setState({ currQuestion: id }) }