反应并渲染标签

时间:2016-11-04 17:56:09

标签: reactjs frontend

因此,我通过“renderTitles()”渲染标签的标题。当我点击标题并将其设置为“选定”道具时,我需要获取我的标签的索引。 “handleClick()”显示当前索引 - 没关系,但我不明白为什么“选中”的状态不一样。哪里我错了?

const tabTitle = ['Prices', 'Description', 'Analytics'];

class Tabs extends React.Component {
    
    constructor(props) {
        super(props);
            
        this.state = {
            selected: 0
        }
    }
    
    handleClick(index) {
        this.setState({ selected: index })
        console.log(this.state.selected)
        console.log(index)
    }
    
    renderTitles() {
        return tabTitle.map( (el, index) => {
            return (
                <li key={index}>
                    <a href="#"
                        onClick={this.handleClick.bind(this, index)}>
                        {el} 
                    </a>
                </li>
            );
        })
    }
    
    render() {
        return (
            <div>
                <ul>{this.renderTitles()}</ul>
            </div>
        );
    }
}

Tabs.propTypes = {
    selected: React.PropTypes.number
}

ReactDOM.render(
  <Tabs />,
  document.getElementById('root')
);
<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="root"></div>

1 个答案:

答案 0 :(得分:0)

this.setState is asynchronous。如果您想查看selected设置的内容,请在超时后执行此操作:

this.setState({ selected: index })
setTimeout(function () {
  console.log(this.state.selected);
}, 1000);