【问题标题】:Insert React state variable into rendered array将 React 状态变量插入渲染数组
【发布时间】:2021-08-27 20:44:37
【问题描述】:

如何将“word”变量插入到渲染对象中,如下面的代码所示 我已经尝试过 $word 和 $word 但没有任何效果

import React, {useState, useEffect} from 'react'

export default function dictionary() {
  const data = {
    "ABATE": {
      "MEANINGS": {
        "2": [
          "Verb",
          "become less in amount or intensity",
          [ "Decrease", "Diminish", "Lessen", "Fall" ],
          [ "The storm abated", "The rain let up after a few hours" ]
        ]
      },
      "ANTONYMS": [],
      "SYNONYMS": [ "Slack off", "Slack", "Abate", "Die away", "Slake" ]
    },
    "ABATEMENT": {
      "MEANINGS": {
        "2": [
          "Noun",
          "the act of abating",
          [ "Moderation", "Mitigation" ],
          [ "laws enforcing noise abatement" ]
        ]
      },
      "ANTONYMS": [],
      "SYNONYMS": [ "Abatement", "Suspension", "Reprieve", "Hiatus", "Respite" ]
    },
  };
  const [word, setWord] = useState('ABATE')

  return ( 
    <>
      <div>
        <label>Word</label>
        <input type="text" value={word} onChange={(e) => setWord(e.target.value)} />
      </div>
      <div className="container pt-n5" >
        <div className="jumbotron d-flex justify-content-center " >
          <div>
            <b> Meaning:</b>
            <p>{data.$`word`?.MEANINGS[0]}</p> {word} <br />
            <b> Meaning:</b>   <p>{data.$word?.MEANINGS[1]}</p>
            <b> Meaning:</b>   <p>{data.$word?.MEANINGS[2]}</p>
          </div>
        </div>
      </div>
    </>
  );
}

【问题讨论】:

    标签: arrays reactjs object react-hooks


    【解决方案1】:

    使用bracket-notation

    data[word]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-21
      • 2020-06-26
      • 2017-02-03
      • 2018-03-24
      • 2019-03-22
      • 2019-09-23
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多