reactjs – 单击项目时更改React中列表中的项目
我对ReactJS很陌生,我很难理解不同的组件如何相互通信.
我有一个组件将呈现一个列表,每个列表项是一个不同的组件.我想保持组件尽可能小. 现在,每个列表项都可以具有名为active的属性,如果该属性设置为true,则会添加一个附加类. 这是在组件中定义单个项的类. 请参阅以下代码,以了解定义单个列表项的组件: export default class OfficeRibbonTab extends React.Component { constructor(props) { super(props); this.state = { active: props.active ? props.active : false } // Assign all the correct event handlers. this.setActive = this.setActive.bind(this); } setActive() { this.setState({active: true}); } render() { // When the tab is defined as active,add the "active" class on it. if (this.state.active) { var tabClassName = "active"; } return <li onClick={this.setActive} className={tabClassName}>{this.props.tabName}</li>; } } 所以,我有propery active传递给这个组件,我存储在组件状态. 下面的代码是我的列表的概述: export default class OfficeRibbon extends React.Component { constructor(props) { // Call the 'base' constructor. super(props); } render() { var tabs = []; // Loop over all the tab elements and define how the element should be rendered. for (var i = 0; i < this.props.dataSource.tabs.length; i ++) { if (i == 1) { tabs.push(<OfficeRibbonTab active={true} key={this.props.dataSource.tabs[i].name} tabName={this.props.dataSource.tabs[i].name}></OfficeRibbonTab>); } else { tabs.push(<OfficeRibbonTab key={this.props.dataSource.tabs[i].name} tabName={this.props.dataSource.tabs[i].name}></OfficeRibbonTab>); } } return (<div> <div className="wrap-top"> <OfficeRibbonTitle title={this.props.title}/> <ul className="tabs"> {tabs} </ul> </div> </div>); } } 它看起来不像火箭科学,但我想用React的方式做它而不重新发明轮子. 谁可以指导我朝正确的方向? 亲切的问候 解决方法
看起来OfficeRibbonTab管理自己的状态,这很好,但它永远不会通知其父组件状态更改.最常见的方法是为每个子组件提供一个回调函数,以便它可以回传给父组件:
例如,OfficeRibbon现在将包含一个函数handleTabSelect,该函数作为prop传递给每个OfficeRibbonTab.在OfficeRibbonTab中,单击选项卡时,只需调用回调,并传入选定选项卡的索引或ID: OfficeRibbonTab.jsx setActive(tabIndex) { this.props.handleTabSelect(tabIndex); } OfficeRibbon.jsx handleTabSelect(tabIndex) { this.setState({activeIndex: tabIndex}); } 现在在OfficeRibbon中,您可以通过索引或所选标识符再次更新状态以设置activeIndex或activeId.通过在OfficeRibbon中设置状态,我们必须强制其子项的render().因此,当我们迭代render()时,我们只是简单地将迭代器的索引与状态的activeIndex匹配: <OfficeRibbonTab active={index === this.state.activeIndex} onClick={this.handleTabSelect} ... /> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |