我正在开发类似App的测验,其中我有一个问题和一整套答案。我的目的是根据正确或错误的答案更改答案元素的背景颜色。我尝试了以下技术,但它正在改变我所有答案元素的颜色。从'react'导入React;
function Book(props){
let onClick = props.onClick;
return(
<div className="answer"
style={{backgroundColor:props.highlight}}
onClick={()=>{onClick(props.title);}}
>
<h1>{props.title}</h1>
</div>
)
}
export default Book;
这是我正在使用书本组件的组件
import React from 'react';
import AuthorQuiz from '../AuthorQuiz';
import Book from './book';
function Turn(props){
let highlight = props.highlight;
console.log(props);
function highlightToBgColor(highlight){
const mapping = {
none:'',
'correct':'green',
'wrong':'red'
}
return mapping[highlight];
}
return(
<div className="row turn">
<div className="col-4 offset-1">
<img src={props.author.imageUrl} className="auhtorimage" alt="Auhtor"/>
</div>
<div className="col-6">
{props.books.map((title) => <Book title={title} key={title} highlight={highlightToBgColor(highlight)} onClick={props.onAnswerSelected}/>)}
</div>
</div>
)
}
export default Turn;
以下为输出
任何人都可以,请问我该如何实现。
这是更改所选列表项目颜色的方法。
示例应用
class App extends React.Component {
state = {
arr: [
{ id: 1, name: "profile", title: "Profile" },
{ id: 2, name: "recruit", title: "Recruitment" },
{ id: 3, name: "arts", title: "Arts" },
{ id: 4, name: "talents", title: "Talents" },
{ id: 5, name: "affection", title: "Affection" }
],
selected: ""
};
changeColor = id => {
this.setState ({ selected: id });
};
render() {
const { selected, arr } = this.state;
console.log(selected)
return (
<div>
<h2>Click to items</h2>
<ul>
{arr.map(({ name, id, title }) => (
<li key={id}>
<h3
style={{
color: selected === id ? "red" : ""
}}
onClick={() => this.changeColor(id)}
name={name}
>
{title}
</h3>
</li>
))}
</ul>
</div>
);
}
}
工作示例live demo