Reactjs

时间:2016-04-25 01:14:27

标签: javascript reactjs

这可能会非常简单。但我很难弄清楚我的反应组件的编写方式有什么问题。这是组件代码。

import React, { Component, PropTypes } from 'react';
import styles from './Menu.css';
import SubMenu from './SubMenu';
import classNames from 'classnames/bind';

let cx = classNames.bind(styles);

export default class Menu extends Component{
static propTypes ={
  menuData:PropTypes.array.isRequired
};


constructor(props){
super(props);
 this.state = {menuOpenedLabel:""};
};
menuClick(label){
  this.state.menuOpenedLabel = label;
};

render(){
  let menus = this.props.menuData.map(function(menuItem){
  let handleClick = this.menuClick.bind(this,menuItem.label);
  return (<li key={menuItem.label}>
    <a onClick={handleClick}>{menuItem.label}</a>
    <SubMenu subMenu={menuItem.submenu} isVisible={this.state.menuOpenedLabel === menuItem.label}/>
  </li>);
  });

return (<nav>
  <ul className={styles.menu}>{(menus)}</ul>
</nav>);
 }
}

这是我在chrome中遇到的错误。

 Uncaught TypeError: Cannot read property 'menuClick' of undefined

起初我以为是因为在map函数中使用this,但显然这段代码是正确的。基于此链接。

https://facebook.github.io/react/tips/expose-component-functions.html

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

好的我明白了! map()有第二个参数,用来控制它的值。

let menus = this.props.menuData.map(function(menuItem){
  let handleClick = this.menuClick.bind(this,menuItem.label);
  return (<li key={menuItem.label}>
    <a onClick={handleClick}>{menuItem.label}</a>
    <SubMenu subMenu={menuItem.submenu} isVisible={this.state.menuOpenedLabel === menuItem.label}/>
  </li>);
}, this);

答案 1 :(得分:0)

Your component is fine, but map stuff can be confusing to look at sometimes. I find this a useful chunk of code, maybe it will help you even though you already figured it out:) Just a way of organizing a map and you get the index, too.

render() {
    const { stuffs } = this.state;
    return (
      <div>
      {stuffs.map((stuff, i) => {
          return(
               <Components key={i} funStuff={stuff.fun} />
          );
      })}
      </div>
    )
}