html 字符串数组转换为 JSX

html strings array convert to JSX

`import React from 'react'

export default function Quiz(props){


    // generate random index without duplicates
    function generateRandomIndex(){
        const randomNumArr=[]

        for (var a = [0, 1, 2, 3], i = a.length; i--; ) {
            var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
            randomNumArr.push(random)
        }
        return randomNumArr
    }

    let randomNumbers = generateRandomIndex()

    let spreadOptions = ()=>{

        let optionsHtmlArray = []
            for(let i=0; i<props.answers.length; i++){
                optionsHtmlArray.push(`<span className='answers' key=${i} style={${{backgroundColor: props.correct===props.answers[i] ? "green" : "red"}}}>
                { ${props.answers[i]} } </span>`)


            }
            return optionsHtmlArray
        }


    return (
    
      <div className='Quiz'>
        <h3 className='question'>{props.question}</h3>

        <div className='answers_div'>
         { spreadOptions()[randomNumbers[0]] }
         { spreadOptions()[randomNumbers[1]] }
         { spreadOptions()[randomNumbers[2]] }
         { spreadOptions()[randomNumbers[3]] }
        </div>
        <hr className='hr'/>
      </div>)

}

'

 '//this is from App.js
// fetch to API when first render to save data to the state, 
  // and fetch depending on the sate of showOverlay
  React.useEffect(() => {

    fetch("https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple")
        .then(res => res.json())
        .then(data => {
          setQuestions(data.results)
          //after set questions state that comes from fetch request
          //and set the custom questions with some properties I need
          setCustomQuestions(prevQuestions=>{
            let newArr=[]
            for(let i=0; i<data.results.length; i++){
              newArr.push({question: data.results[i].question, 
                           questionId: nanoId(),
                           answers: [data.results[i].correct_answer].concat(data.results[i].incorrect_answers),
                           correct: data.results[i].correct_answer})
            }
 
            return newArr
          })
          
        })
}, [])

  // Quiz component properties
  const customQuestionsArr = customQuestions.map(question => {
    return < Quiz
      key={question.questionId}
      question={question.question}
      answers={question.answers}
      correct={question.correct}
   />

  })'

大家好,我正在尝试在测验组件中呈现答案的所有选项,但是,
spreadOptions() returns 一个 html 字符串数组作为答案 我必须解析为 JSX 才能使其正常工作。

  1. 我尝试安装 react-html-parser,但没有成功,每次我尝试通过 npm 安装依赖项时都会出现一堆错误
  2. 我危险地尝试了 SetInnerHTML,但也没有用

您能否提供您尝试传递给 Quiz 组件的道具?

下面是修改了 spreadOptionsjsx return 的代码片段。我无法测试此代码,但如果您可以提供示例道具,我会更新它。

let spreadOptions = props.answers.map((a, i) => (
  <span 
    key={i}
    className='answers' 
    style={{ 
      backgroundColor: props.correct === a ? 'green' : 'red',
    }}
    >
      {a}
  </span>
));

return (
  <div className="Quiz">
    <h3 className="question">{props.question}</h3>

    <div className="answers_div">
      {spreadOptions}
    </div>
    <hr className="hr" />
  </div>
);