我制作了一个简单的基本选项卡组件,我是ReactJS的初学者,所以任何关于代码功能的建议都会受到极大的赞赏。
import React from 'react';
class Tabs extends React.Component {
constructor() {
super();
this.state = {
activeIndex : 0
}
}
handleOnClick(key, event) {
event.preventDefault();
this.setState({
activeIndex : key
});
}
renderNavItem(key) {
let tab = this.props.children[key];
return (
<li key={ key } className={ this.state.activeIndex == key ? 'active' : ''}>
<a href="#" onClick={ this.handleOnClick.bind(this, key) }>{ tab.props.title }</a>
</li>
);
}
render() {
let index = 0;
let active = this.state.activeIndex;
let tabs = React.Children.map(this.props.children, function (child) {
return React.cloneElement(child, {
active : child.props.active === true ? true : (active == index++)
});
});
return (
<div className={ this.props.className }>
<ul className="tabs-nav">
{ Object.keys(this.props.children).map(this.renderNavItem.bind(this)) }
</ul>
<div className="tabs-content">
{ tabs }
</div>
</div>
)
}
}
class Tab extends React.Component {
render() {
return (
<div className={ "tab-panel" + (this.props.active ? ' active' : '') }>
{ this.props.children }
</div>
)
}
}
Tab.defaultProps = {
active : false
};
export default {
Tabs,
Tab
};import React from 'react';
import {Tabs, Tab} from './Tabs';
class App extends React.Component {
render() {
return (
<Tabs className="tabs-wrapper">
<Tab active="true" title="Tab One">Tab One content</Tab>
<Tab title="Tab Two">
<div>Tab Two Content</div>
</Tab>
</Tabs>
);
}
}
React.render(
<App/>,
document.getElementById('react_example')
);http://jsbin.com/hajokofavu/edit?js,输出
发布于 2016-06-21 20:33:22
由于这里没有那么多代码可供审查,所以我回顾了一些样式要点:
您在代码中使用了一些奇怪的空格:
handleOnClick(键,事件){ event.preventDefault();this.setState({ activeIndex : key // ^-空格不应该在属性冒号}之前);}
这不一定是错误的,但是有很多空的空格行使你的程序看起来比它应该做的更好。
child.props.active ===真的吗?真:(active == index++)
您不需要将属性与布尔值进行比较,因为只需指定变量而不进行比较就可以执行布尔比较:
var thing = true;
console.log(thing === true ? 1 : 2); // identical
console.log(thing ? 1 : 2); // identical您在使用分号时也有一些不一致之处:
构造函数(){ super();this.state ={ activeIndex :0}}
发布于 2018-08-20 13:11:27
除了代码中的一个性能问题之外,每件事情看起来都很好。您已经有了activeIndex,因此不需要再遍历整个地图来呈现选项卡内容。
下面是修改后的Tabs类:
class Tabs extends React.Component {
constructor() {
super();
this.state = {
activeIndex : 0
}
}
handleOnClick(key, event) {
event.preventDefault();
this.setState({
activeIndex : key
});
}
renderNavItem(key) {
let tab = this.props.children[key];
return (
<li key={ key } className={ this.state.activeIndex == key ? 'active' : ''}>
<a href="#" onClick={ this.handleOnClick.bind(this, key) }>{ tab.props.title }</a>
</li>
);
}
render() {
let active = this.state.activeIndex;
let tabs = this.props.children[active];
return (
<div className={ this.props.className }>
<ul className="tabs-nav">
{ Object.keys(this.props.children).map(this.renderNavItem.bind(this)) }
</ul>
<div className="tabs-content">
{ tabs.props.children }
</div>
</div>
)
}
}https://codereview.stackexchange.com/questions/132599
复制相似问题