簡體   English   中英

如何在 ReactJS 中的字符串內呈現跨度數組?

[英]How to render an array of spans inside a string in ReactJS?

我有一個span元素數組,需要在另一個 static 文本中呈現。

最終結果示例:將312以正確的順序here the bold numbers are the spans

這是我的代碼

generateQuestion() {
    const newState = { ...this.state };
    let numbers= newState.numbers.map((item, index) => <span style={{color: "red"}}>{item.number}</span>)
    let textQuestion = `Place the numbers ${numbers[0]}, ${numbers[1]} and ${numbers[2]} in the right order.`;

    return (
        <div>{textQuestion}</div>
    );
}

問題是我在渲染時得到這個Place the numbers [object Object], [object Object] and [object Object] in the right order

當我直接渲染numbers數組時,我得到了跨度

return (
        <div>{numbers}</div>
);

我該如何解決這個問題?

您正在嘗試在字符串中呈現對象,正確的方法是使用 jsx 而不是字符串:

generateQuestion() {
  const newState = { ...this.state };
  let numbers= newState.numbers.map((item, index) => <span style={{color: "red"}}>{item.number}</span>)
  let textQuestion = <div>Place the numbers {numbers[0]}, {numbers[1]} and {numbers[2]} in the right order.<div>;

  return (
      {textQuestion}
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM