【问题标题】:UPD: React doesn't return HTML elements from functionsUPD:React 不会从函数返回 HTML 元素
【发布时间】:2020-05-03 16:05:31
【问题描述】:

我需要从 React.Component 中的 JSON 创建一个嵌套的手风琴菜单。对象对象的每个键都必须是在单击时显示嵌套项的按钮(如果值不为空)。我有两个函数可以为键创建按钮和为值创建隐藏的 div,但它们不会出现在 HTML 代码中。

menuItems.json

{
  "item1": {
    "nestedItem1": null,
    "nestedItem2": {
      "deeplyNetstedItem1": null
    }
  },
  "item2": null,
  "item3": null,
  "item4": {
    "nestedItem3": null
  }
}

DropdownList.jsx (UPD)

import React from "react";

class DropdownList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.data
    };
    this.createListData = this.createListData.bind(this);
    this.createButton = this.createButton.bind(this);
    this.createHidden = this.createHidden.bind(this);
  }

  createButton = (item) => {
    return <button className='accordion'>{item}</button>
  }

  createHidden = (item) => {
    return <div className='panel'>{item}</div>
  }

  createListData = (data) => {
    for (let [key, value] of Object.entries(data)) {
      if (value && typeof(value) == "object") {
        console.log(key, value);
        this.createButton(key);
        this.createListData(value);
      } else {
        this.createHidden(key);
        console.log(key);
      }
    }
  }

  render() {
    return <div>{this.createListData(this.state.data)}</div>
  }
}

export default DropdownList;

App.js

import React from "react";
import DropdownList from "./DropdownList/DropdownList";
import data from "./menuItems.json";

function App() {
  return <DropdownList data={data} />;
}

export default App;

【问题讨论】:

    标签: javascript html json reactjs return


    【解决方案1】:

    这会起作用

    renderObject = obj => {
        return obj === 'object' ? Object.values(obj).map(val =>
          typeof val === 'object' ? (
            this.renderObject(val)
          ) : (
            <li>{val ? val : 'Any message'}</li>
          ),
        ) : <li>Any message</li>
      };
      render() {
        return <div>{this.renderObject(this.state.data)}</div>;
      }
    

    【讨论】:

    • 我需要从对象中输出所有项目,这种方式只输出键
    • 好的,试试这个renderObject = obj =&gt; { return Object.values(obj).map(val =&gt; typeof val === 'object' ? ( this.renderObject(val) ) : ( &lt;li&gt;{val ? val : ''}&lt;/li&gt; ), ); }; render() { return &lt;div&gt;{this.renderObject(this.state.data)}&lt;/div&gt;; }
    • TypeError: 无法将 undefined 或 null 转换为对象
    • 我更新了上面的代码试试,不会报错
    猜你喜欢
    • 2019-02-19
    • 2019-02-04
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2011-04-08
    • 2021-06-07
    • 2017-04-07
    相关资源
    最近更新 更多