使用React处理子组件

时间:2016-07-27 18:10:59

标签: javascript reactjs ecmascript-6

我正在尝试使用React重建this

我有一个看起来像这样的集合:

[
        {
            title: "Google",
            url: "www.google.com"
            tab: "Tab A",
            section: "Section A"
        },
        {
            title: "Facebook",
            url: "www.facebook.com"
            tab: "Tab B",
            section: "Section A"
        },
        {
            title: "Yahoo",
            url: "www.yahoo.com"
            tab: "Tab B",
            section: "Section B"
        },
        {
            title: "Reddit",
            url: "www.reddit.com"
            tab: "Tab C",
            section: "Section A"
        }
    ]

我已经做到了这一点,我可以通过调用HomeNav组件中的Tab组件来创建标签:

    class Tabs extends React.Component {

  constructor(props) {
    super(props)
    this.state = { items: [], index: null }
  }

  componentDidMount() {
    // Keep the scope of this function so it can be used in checkFlag
    this.setState({
      items: this.props.items,
      index: this.props.index
    })
  }

  render() {
    var {item, index} = this.props
    return (
      <details key={item} id={"details-panel" + (++index)}>
        <summary>{item}</summary>
        <p>{"Something something" + item}</p>
      </details>
    )
  }
};

class HomeNav extends React.Component {

  constructor(props) {
    super(props)
    this.state = { items: [] }
  }

  componentDidMount() {
    // Keep the scope of this function so it can be used in checkFlag
    this.setState({
      items: data
    })
  }

  render() {
    let uniqueTabs = _.uniq(_.map(data, x => x.tab)).sort()

    let tabs = uniqueTabs.map((item, index) => {
      return (
        <Tabs key={item} item={item} index={index} />
      )
    })

    return (
      <section>
        <h3>Home Nav</h3>
        <div className="wb-tabs">
          <div className="tabpanels">
            {tabs}
          </div>
        </div>
      </section>
    )
  }
};

根据我的理解,我可能需要每个部分的子组件和每个链接的另一个组件?所以我打破了这样的HTML:

<!-- Main Component -->
<section>
  <div class="wb-tabs">
    <div class="tabpanels">
      {{TAB}}
    </div>
  </div>
</section>

<!-- {{TAB} -->}
<details id="details-panel1">
  <summary>{{item.tab}}</summary>
  {{SECTION}}
</details>

<!-- {{SECTION}} -->
<div class="col-md-9">
  <h2 class=" bg-corp-med  h5">What’s new?</h2>
  <ul>
    {{LINKS}}
  </ul>
</div>

<!-- {{LINKS}} -->
<li>
  <a href="{{item.url}}">
    <strong>
      <span class="small">{{item.title}}</span>
    </strong>
  </a>
</li>

我也不确定我是如何将每个对象放在相应的标签和部分中的。任何帮助都会很棒

Fiddle

0 个答案:

没有答案