Reactjs 如何更改背景色
我是一个新的反应和它的工作真的很有趣。根据我目前的应用程序,这是一个测验应用程序,如果用户选择任何选项,它应该改变背景颜色为红色或绿色。我正在使用语义用户界面,并向菜单项传递带有单击事件的数据,在该事件中,我正在存储用户选择的答案。但我无法改变正确答案或错误答案的颜色。这是代码Reactjs 如何更改背景色,reactjs,react-redux,Reactjs,React Redux,我是一个新的反应和它的工作真的很有趣。根据我目前的应用程序,这是一个测验应用程序,如果用户选择任何选项,它应该改变背景颜色为红色或绿色。我正在使用语义用户界面,并向菜单项传递带有单击事件的数据,在该事件中,我正在存储用户选择的答案。但我无法改变正确答案或错误答案的颜色。这是代码 import React, { Component } from 'react'; import { Container, Segment, Item, Divider, Button, Icon
import React, { Component } from 'react';
import {
Container,
Segment,
Item,
Divider,
Button,
Icon,
Message,
Menu,
Header
} from 'semantic-ui-react';
import Swal from 'sweetalert2';
import Loader from '../Loader';
import Countdown from '../Countdown';
import Result from '../Result';
import Offline from '../Offline';
import he from 'he';
import { getRandomNumber } from '../../utils/getRandomNumber';
class Quiz extends Component {
constructor(props) {
super(props);
this.state = {
quizData: null,
isLoading: true,
questionIndex: 0,
correctAnswers: 0,
userSlectedAns: null,
quizIsCompleted: false,
questionsAndAnswers: [],
isOffline: false,
bgColor: ""
};
this.timeTakesToComplete = undefined;
this.setData = this.setData.bind(this);
this.handleItemClick = this.handleItemClick.bind(this);
this.handleNext = this.handleNext.bind(this);
this.timesUp = this.timesUp.bind(this);
this.timeAmount = this.timeAmount.bind(this);
this.renderResult = this.renderResult.bind(this);
this.retakeQuiz = this.retakeQuiz.bind(this);
this.startNewQuiz = this.startNewQuiz.bind(this);
this.resolveError = this.resolveError.bind(this);
}
componentDidMount() {
const { API } = this.props;
fetch(API)
.then(respone => respone.json())
.then(result => setTimeout(() => this.setData(result.results), 1000))
.catch(error => setTimeout(() => this.resolveError(error), 1000));
}
resolveError(error) {
if (!navigator.onLine) {
this.setState({ isOffline: true });
console.log('Connection problem');
} else {
this.setState({ isOffline: true });
console.log('API problem ==> ', error);
}
}
setData(results) {
if (results.length === 0) {
const message =
"The API doesn't have enough questions for your query<br />" +
'(ex. Asking for 50 questions in a category that only has 20).' +
'<br /><br />Please change number of questions, difficulty level ' +
'or type of questions.';
return Swal.fire({
title: 'Oops...',
html: message,
type: 'error',
timer: 10000,
onClose: () => {
this.props.backToHome();
}
});
}
const quizData = results;
const { questionIndex } = this.state;
const outPut = getRandomNumber(0, 3);
const options = [...quizData[questionIndex].incorrect_answers];
options.splice(outPut, 0, quizData[questionIndex].correct_answer);
this.setState({ quizData, isLoading: false, options, outPut });
}
handleItemClick(e, { name }) {
const {
userSlectedAns,
quizData,
questionIndex,
} = this.state;
this.setState({ userSlectedAns: name });
console.log(name);
if (userSlectedAns === he.decode(quizData[questionIndex].correct_answer)) {
this.state.active = 'green';
}
}
handleNext() {
const {
userSlectedAns,
quizData,
questionIndex,
correctAnswers,
questionsAndAnswers
} = this.state;
let point = 0;
if (userSlectedAns === he.decode(quizData[questionIndex].correct_answer)) {
point = 1;
}
questionsAndAnswers.push({
question: he.decode(quizData[questionIndex].question),
user_answer: userSlectedAns,
correct_answer: he.decode(quizData[questionIndex].correct_answer),
point
});
if (questionIndex === quizData.length - 1) {
this.setState({
correctAnswers: correctAnswers + point,
userSlectedAns: null,
isLoading: true,
quizIsCompleted: true,
questionIndex: 0,
options: null,
questionsAndAnswers
});
return;
}
const outPut = getRandomNumber(0, 3);
const options = [...quizData[questionIndex + 1].incorrect_answers];
options.splice(outPut, 0, quizData[questionIndex + 1].correct_answer);
this.setState({
correctAnswers: correctAnswers + point,
questionIndex: questionIndex + 1,
userSlectedAns: null,
options,
outPut,
questionsAndAnswers
});
}
timesUp() {
this.setState({
userSlectedAns: null,
isLoading: true,
quizIsCompleted: true,
questionIndex: 0,
options: null
});
}
timeAmount(timerTime, totalTime) {
this.timeTakesToComplete = {
timerTime,
totalTime
};
}
renderResult() {
setTimeout(() => {
const { quizData, correctAnswers, questionsAndAnswers } = this.state;
const { backToHome } = this.props;
const resultRef = (
<Result
totalQuestions={quizData.length}
correctAnswers={correctAnswers}
timeTakesToComplete={this.timeTakesToComplete}
questionsAndAnswers={questionsAndAnswers}
retakeQuiz={this.retakeQuiz}
backToHome={backToHome}
/>
);
this.setState({ resultRef, questionsAndAnswers: [] });
}, 2000);
}
retakeQuiz() {
const { quizData, questionIndex } = this.state;
const outPut = getRandomNumber(0, 3);
const options = [...quizData[questionIndex].incorrect_answers];
options.splice(outPut, 0, quizData[questionIndex].correct_answer);
this.setState({
correctAnswers: 0,
quizIsCompleted: false,
startNewQuiz: true,
options,
outPut
});
}
startNewQuiz() {
setTimeout(() => {
this.setState({ isLoading: false, startNewQuiz: false, resultRef: null });
}, 1000);
}
render() {
const {
quizData,
questionIndex,
options,
userSlectedAns,
isLoading,
quizIsCompleted,
resultRef,
startNewQuiz,
isOffline
// outPut,
// correctAnswers,
} = this.state;
// console.log(userSlectedAns);
// console.log(questionIndex, outPut);
// console.log('Score ==>', correctAnswers);
if (quizIsCompleted && !resultRef) {
this.renderResult();
// console.log('Redirecting to result');
}
if (startNewQuiz) {
this.startNewQuiz();
}
return (
<Item.Header>
{!isOffline && !quizIsCompleted && isLoading && <Loader />}
{!isOffline && !isLoading && (
<Container>
<Segment>
<Item.Group divided>
<Item>
<Item.Content>
<Item.Extra>
<Header as="h1" block floated="left">
<Icon name="info circle" />
<Header.Content>
{`Question No.${questionIndex + 1} of ${
quizData.length
}`}
</Header.Content>
</Header>
<Countdown
countdownTime={this.props.countdownTime}
timesUp={this.timesUp}
timeAmount={this.timeAmount}
/>
</Item.Extra>
<br />
<Item.Meta>
<Message size="huge" floating>
<b>{`Q. ${he.decode(
quizData[questionIndex].question
)}`}</b>
</Message>
<br />
<Item.Description>
<h3>Please choose one of the following answers:</h3>
</Item.Description>
<Divider />
<Menu vertical fluid size="massive">
{options.map((option, i) => {
let letter;
switch (i) {
case 0:
letter = 'A.';
break;
case 1:
letter = 'B.';
break;
case 2:
letter = 'C.';
break;
case 3:
letter = 'D.';
break;
default:
letter = i;
break;
}
const decodedOption = he.decode(option);
return (
<Menu.Item
key={decodedOption}
name={decodedOption}
active={userSlectedAns === decodedOption}
onClick={this.handleItemClick}
// style={{backgroundColor: this.state.bgColor }}
>
<b style={{ marginRight: '8px' }}>{letter}</b>
{decodedOption}
</Menu.Item>
);
})}
</Menu>
</Item.Meta>
<Divider />
<Item.Extra>
<Button
primary
content="Next"
onClick={this.handleNext}
floated="right"
size="big"
icon="right chevron"
labelPosition="right"
disabled={!userSlectedAns}
/>
</Item.Extra>
</Item.Content>
</Item>
</Item.Group>
</Segment>
<br />
</Container>
)}
{quizIsCompleted && !resultRef && (
<Loader text="Getting your result." />
)}
{quizIsCompleted && resultRef}
{isOffline && <Offline />}
</Item.Header>
);
}
}
export default Quiz;
import React,{Component}来自'React';
进口{
集装箱,
段
项目,,
分隔器,
按钮
偶像
消息
菜单,
标题
}来自“语义ui反应”;
从“sweetalert2”进口棉签;
从“../Loader”导入加载程序;
从“../Countdown”导入倒计时;
从“../Result”导入结果;
从“../Offline”脱机导入;
从“he”中导入he;
从“../../utils/getRandomNumber”导入{getRandomNumber};
类扩展组件{
建造师(道具){
超级(道具);
此.state={
quizData:null,
孤岛加载:是的,
问题索引:0,
正确答案:0,
userSlectedAns:null,
quizIsCompleted:错,
问题与答案:[],
伊索夫林:错,
bgColor:“
};
this.timeTakesToComplete=未定义;
this.setData=this.setData.bind(this);
this.handleItemClick=this.handleItemClick.bind(this);
this.handleNext=this.handleNext.bind(this);
this.timesUp=this.timesUp.bind(this);
this.timeAmount=this.timeAmount.bind(this);
this.renderResult=this.renderResult.bind(this);
this.retakeQuit=this.retakeQuit.bind(this);
this.startnewquick=this.startnewquick.bind(this);
this.resolvererror=this.resolvererror.bind(this);
}
componentDidMount(){
const{API}=this.props;
获取(API)
.then(respone=>respone.json())
.then(result=>setTimeout(()=>this.setData(result.results),1000))
.catch(error=>setTimeout(()=>this.resolvererror(error),1000));
}
resolveError(错误){
如果(!navigator.onLine){
this.setState({isOffline:true});
console.log(“连接问题”);
}否则{
this.setState({isOffline:true});
log('API问题==>',错误);
}
}
setData(结果){
如果(results.length==0){
常量消息=
“API没有足够的问题供您查询
”+
"(例如,在只有20个问题的类别中提出50个问题)"+
“
请更改问题数量、难度级别”+
“或问题类型。”;
回注水沟火({
标题:“哎呀……”,
html:message,
键入:“错误”,
计时器:10000,
onClose:()=>{
this.props.backToHome();
}
});
}
const quizData=结果;
const{questionIndex}=this.state;
常量输出=getRandomNumber(0,3);
const options=[…quizData[questionIndex]。回答不正确];
选项。拼接(输出,0,quizData[questionIndex]。正确答案);
this.setState({quizData,isload:false,options,outPut});
}
handleItemClick(e,{name}){
常数{
userSlectedAns,
基兹达塔,
问题索引,
}=本州;
this.setState({userSlectedAns:name});
console.log(名称);
if(userSlectedAns===he.decode(quizData[questionIndex].正确答案)){
this.state.active='green';
}
}
handleNext(){
常数{
userSlectedAns,
基兹达塔,
问题索引,
正确答案,
问答
}=本州;
设点=0;
if(userSlectedAns===he.decode(quizData[questionIndex].正确答案)){
点=1;
}
问题和答案({
问题:he.decode(quizData[questionIndex].question),
用户回答:userSlectedAns,
正确答案:he.decode(quizData[questionIndex]。正确答案),
指向
});
if(questionIndex==quizData.length-1){
这是我的国家({
正确答案:正确答案+分数,
userSlectedAns:null,
孤岛加载:是的,
奎兹完成:是的,
问题索引:0,
选项:null,
问答
});
返回;
}
常量输出=getRandomNumber(0,3);
const options=[…quizData[questionIndex+1]。回答不正确];
选项。拼接(输出,0,quizData[questionIndex+1]。正确答案);
这是我的国家({
正确答案:正确答案+分数,
问题索引:问题索引+1,
userSlectedAns:null,
选项,
产出,
问答
});
}
timesUp(){
这是我的国家({
userSlectedAns:null,
孤岛加载:是的,
奎兹完成:是的,
问题索引:0,
选项:空
});
}
timeAmount(timerTime,totalTime){
此参数为0.timeTakesToComplete={
时间,
总时间
};
}
renderResult(){
设置超时(()=>{
const{quizData,correctAnswers,questionsAndAnswers}=this.state;
const{backToHome}=this.props;
常数resultRef=(
);
this.setState({resultRef,questions and answers:[]});
}, 2000);
}
重考{
const{quizData,questionIndex}=this.state;
常量输出=getRandomNumber(0,3);
const options=[…quizData[questionIndex]。回答不正确];
选项。拼接(输出,0,quizData[questionIndex]。正确答案);
这是我的国家({
正确答案:0,
quizIsCompleted:错,
新测验:是的,
选项,
输出
});
}
startnewquick(){
设置超时(()=>{
this.setState({isLoading:false,StartNew-Quike:false,resultRef:null});
}, 1000);
}
render(){
常数{
基兹达塔,
问题索引,
选项,
userSlectedAns,
孤岛,
奎兹完成了,
结果:,
开始新测验,
异氟烷
//产出,
//正确答案,
}=本州;
//console.lo
if (userSlectedAns === he.decode(quizData[questionIndex].correct_answer)) {
this.state.active = 'green';
}
if (userSlectedAns === he.decode(quizData[questionIndex].correct_answer)) {
this.setState({
active: 'green'
});
}