简体   繁体   English

单击组件时如何更改仅通过.map() 渲染的一个反应组件的样式

[英]how to change the style of only one react component that is being render through .map() when the component is clicked

how to change the style of only one react component that is being render through.map() when the component is clicked.单击组件时,如何更改仅通过.map() 渲染的一个反应组件的样式。 I'm trying to make a quiz and I want the component background to change to one color if the right answer is clicked and to another if the wrong answer is clicked.我正在尝试进行测验,如果单击正确答案,我希望组件背景更改为一种颜色,如果单击错误答案,则更改为另一种颜色。 Using only functional components and hooks仅使用功能组件和挂钩

const [correct, setCorrect] = useState(false);

const styles = {
    correct: { backgroundColor: 'green' },
    incorrect: { backgroundColor: 'red' }
};

const DUMMY_QUESTIONS = [
    {
        id: 1,
        question: 'What is the Big O of merge sort?',
        options: [
            { number: 1, answer: 'O(1)'},
            { number: 2, answer: 'O(log n)' },
            { number: 3, answer: 'O(n)' },
            { number: 4, answer: 'O(n log n)' }
        ],
        answer: 'O(n log n)'
    }
];

const handler = opt => {
    if (opt === DUMMY_QUESTIONS[0].answer){
        console.log(opt);
    }
}

return (
    <Fragment>
        <div>
            <Question question={DUMMY_QUESTIONS[0].question} />
        </div>
        <div>
            {DUMMY_QUESTIONS[0].options.map(option =>
                <AnswerOption 
                    key={option.number} 
                    id={option.number}
                    option={option.answer}
                    click={() => {if (option.answer === DUMMY_QUESTIONS[0].answer) setCorrect(true) }}
                    correct={correct} />
            )}
        </div>
    </Fragment>
);

other Component:其他组件:

const AnswerOption = props => {
return (
    <div 
        className={`answer-option ${props.correct && 'answer-option--correct'}`} onClick={() => {props.click(props.option)}} >
        <p>{props.option}</p>
    </div>
);

}; };

The best way to make it work, use the state for selectedAnswer then use selectedAnswer for comparing items inside the style.使其工作的最佳方法是使用 state 作为selectedAnswer然后使用 selectedAnswer 比较样式内的项目。

Also, I did make you another state for the user answers for saving answers on that.另外,我确实为您制作了另一个 state 供用户回答以保存答案。

 const styles = { correct: { backgroundColor: 'green' }, incorrect: { backgroundColor: 'red' } }; const DUMMY_QUESTIONS = [ { id: 1, question: 'What is the Big O of merge sort?', options: [ { number: 1, answer: 'O(1)' }, { number: 2, answer: 'O(log n)' }, { number: 3, answer: 'O(n)' }, { number: 4, answer: 'O(n log n)' } ], answer: 'O(log n)' },{ id: 2, question: 'Another question?', options: [ { number: 1, answer: 'O(1)' }, { number: 2, answer: 'O(log n)' }, { number: 3, answer: 'O(n)' }, { number: 4, answer: 'O(n log n)' } ], answer: 'O(n)' } ]; const App = () => { const [userAnswers, setUserAnswers] = React.useState({}); return( <React.Fragment> {DUMMY_QUESTIONS.map(question => ( <Question question={question} userAnswers={userAnswers} setUserAnswers={setUserAnswers}/> ))} <hr/> <p>Object of user answers: {JSON.stringify(userAnswers)}</p> </React.Fragment> ) } const Question = ({question, userAnswers, setUserAnswers}) => { const [slectedAnswer, setSelectedAnswer] = React.useState(null); const clickHandler = (selected) => { setUserAnswers({...userAnswers,[question.id]:{ selectedAnswer: selected, isCorrect: selected === question.answer }}) setSelectedAnswer(selected); } const styleChecker = (option) => slectedAnswer? slectedAnswer === option? question.answer === slectedAnswer? styles.correct: styles.incorrect: {}: {}; return ( <div> <h4>{question.question}</h4> {question.options.map(option => ( <AnswerOption key={option.number} id={option.number} option={option.answer} onClick={() => slectedAnswer? {}: clickHandler(option.answer)} style={styleChecker(option.answer)} /> ))} </div> ) }; const AnswerOption = ({ option, ...rest }) => ( <div {...rest}> <p>{option}</p> </div> ); ReactDOM.render(<App />, document.getElementById("react"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM