导航菜单在React中不起作用

时间:2017-09-21 13:19:11

标签: reactjs

请帮我修复此导航菜单。这里有些东西不起作用。点击后必须更改点击的单元格。如果你告诉我问题在哪里,我将非常感激

class MenuExample extends React.Component{
constructor(props) {
    super(props);
    this.state = {focused: 0};
}

clicked(index){
    this.setState({focused: index});
};

render: {
    return (
        <div>
            <ul>{ this.props.items.map(function(m, index){
                var style = '';
                if(this.state.focused == index){ style = 'focused'; }
                return <li className={style} onClick={this.clicked.bind(this)}>{m}</li>;
            }) }       
            </ul>

            <p>Selected: {this.props.items[this.state.focused]}</p>
        </div>
    );

}
};

ReactDOM.render(
<MenuExample items={ ['Home', 'Services', 'About', 'Contact us'] } />,
document.getElementById('root')
);

1 个答案:

答案 0 :(得分:1)

它是一个绑定问题,你忘了绑定地图回调方法,这里:

this.props.items.map(function(m, index){.....})

使用arrow function维护上下文,如下所示:

this.props.items.map((m, index) => {.....})

检查工作代码:

&#13;
&#13;
class MenuExample extends React.Component{
  constructor(){
    super();
    this.state = { focused: 0 };
  }

  clicked(index){
    this.setState({focused: index});
  }

  render() {
    return (
      <div>
        <ul>{ this.props.items.map((m, index) => {
                var style = '';
                if(this.state.focused == index){
                    style = 'focused';
                }
                return <li className={style} onClick={this.clicked.bind(this, index)}>{m}</li>
             }) }   
        </ul>
        <p>Selected: {this.props.items[this.state.focused]}</p>
      </div>
    );
  }
}

ReactDOM.render(
  <MenuExample items={ ['Home', 'Services', 'About', 'Contact us'] } />,
  document.getElementById('container')
);
&#13;
* {
    padding:0;
    margin:0;
}

html{
    font:14px normal Arial, sans-serif;
    color:#626771;
    background-color:#fff;
}

body{
    padding:60px;
    text-align: center;
}

ul{
    list-style:none;
    display: inline-block;
}

ul li{
    display: inline-block;
    padding: 10px 20px;
    cursor:pointer;
    background-color:#eee;
    color:#7B8585;
    
    transition:0.3s;
}

ul li:hover{
    background-color:#beecea;
}

ul li.focused{
    color:#fff;
    background-color:#41c7c2;
}

p{
    padding-top:15px;
    font-size:12px;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'/>
&#13;
&#13;
&#13;

Working Fiddle.