【问题标题】:How to create HTML elements from an object in typescript using react如何使用 React 从打字稿中的对象创建 HTML 元素
【发布时间】:2020-07-02 03:07:03
【问题描述】:

我在自己的 .ts 文件中定义了一个类型

export class FakeType  {
    value:{
        name: string,
        id: number
    },
    x: number
 }

我在 .tsx 文件中有一个该对象的实例

let myObj: FakeType;
myObj = {
    value:{
        name: "Foo",
        id: 99
    },
    x: 5
}

如何以编程方式创建与每个字段对应的 html 元素?

我可以手动创建我想要的输出,但如果FakeType 有数百个字段,这将不起作用

return (
    <div>Value: {myObj.value}</div>
    <div>x: {myObj.x}</div>);

请注意,当我在网页上显示字段名称及其值时,我需要访问它。

【问题讨论】:

  • 使用map函数?

标签: html reactjs typescript react-tsx


【解决方案1】:

使用Object.keys(),您可以使用Array.map() 迭代对象的每个键,以返回所需的HTML,并使用myObj[key] 语法显示每个对象键的值。

工作示例:https://codesandbox.io/s/react-stackoverflow-60783297-ozjeu

解释见下面代码中的cmets...

// Your object.
const myObj: FakeType = {
  value: {
    name: "Foo",
    id: 99
  },
  x: 5
};

// Function to get value of an object with key name and unquote value object props.
// Typing `obj: any` is necessary to avoid TypeScript to complain
// about the type of the key value you're trying to retrieve.
const getValue = (obj: any, key: string) => {
  const value = obj[key];
  const stringify = JSON.stringify(value);
  const unquoted = stringify.replace(/"([^"]+)":/g, "$1:");
  return unquoted;
};

// Loop through `myObj` keys and display its value
// using the `getValue()` function implemented above.
return (
  <React.Fragment>
    {Object.keys(myObj).map(key => (
      <div>
        {key}: {getValue(myObj, key)}
      </div>
    ))}
  </React.Fragment>
);

【讨论】:

    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2020-09-16
    • 2020-11-05
    • 2020-12-01
    • 2020-12-14
    相关资源
    最近更新 更多