【问题标题】:html strings array convert to JSXhtml 字符串数组转换为 JSX
【发布时间】:2023-01-29 15:15:25
【问题描述】:
`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() 返回一个 html 字符串数组作为答案 我必须解析为 JSX 才能使其工作。

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

【问题讨论】:

    标签: html reactjs jsx


    【解决方案1】:

    你能提供你试图传递给Quiz组件的道具吗?

    以下是经过修改的代码 sn-p点差选项jsx.我无法测试此代码,但如果您可以提供示例道具,我会对其进行更新。

    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>
    );
    

    【讨论】:

    • 我刚刚添加了一些来自 App 的代码。具有道具和状态信息的js
    • 我试过你的代码,它有效!!!太感谢了!
    • 很高兴听你这样说!乐于帮助!享受编码! :D
    猜你喜欢
    • 2013-10-16
    • 2021-08-24
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多