У меня есть набор вопросов и набор ответов. Каждый ответ - это единственно правильный ответ на один вопрос. Мне нужно выделить правильно выбранный вопрос или ответ при нажатии на него.
Например:
Вот главная страница:
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.info(id)
console.info(type)
this.toggleColour(id)
}
toggleColour = id => {
this.setState({active: !this.state.active})
console.info('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>
)
}
}



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Один из способов приблизиться к этому может быть:
Измените классы таким образом
<Component
className = {this.state.currQuestion === question.id ? 'active' : null}
onClick = {this.handleClick(question.id)}
/>
И вы можете управлять состояниями следующим образом:
handleClick = (id) => {
this.setState({
currQuestion: id
})
}