我有一系列问题和一组答案。每个答案是一个问题的唯一正确答案。我需要在点击时突出显示正确的选定问题或答案。
例如:
这是主要页面:
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>
)
}
}
答案 0 :(得分:1)
解决这个问题的一种方法是:
以这种方式更改课程
<Component
className={this.state.currQuestion === question.id ? 'active' : null}
onClick={this.handleClick(question.id)}
/>
您可以通过以下方式管理状态:
handleClick = (id) => {
this.setState({
currQuestion: id
})
}