<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>react--父子组件通信</title>
<script src='react.js'></script>
<script src='react-dom.js'></script>
<script src='babel.min.js'></script>
<style>
.con{
width:200px;
height: 200px;
border:1px solid green;
margin-top: 10px;
}
.active{
background-color: pink;
}
</style>
</head>
<body>
<div id='example'></div>
<script type='text/babel'>
/*react实现tab面板,有自动播放功能*/
/*三个组件父组件<Tab />两个子组件<Top /><Bottom />*/
/*一个对象,用来存储选项卡的相关信息*/
/*定义头部按钮组件,内容区的个数有头部按钮个数决定*/
class Top extends React.Component{
show(e){
/*获取当前的下标值*/
let index = e.target.getAttribute('data-myIndex');
/*将下标传给父级*/
this.props.tChange(index);
}
render(){
/*定义一个数组来存储按钮*/
let tInput = [];
let tlen = this.props.topValue.length;
for(var i=0;i<tlen;i++){
/*一定要加key否则会报错*/
/*自定义一个属性来存储下标值*/
tInput.push(<input className={this.props.tIndex==i?'active':''} onClick={this.show.bind(this)} type="button" value={this.props.topValue[i]} key={i} data-myIndex={i}/>);
}
/*渲染组件*/
return (
<div>{tInput}</div>
)
}
}
/*定义内容区组件*/
class Bottom extends React.Component{
render(){
let bDiv = [];
/*由头部按钮的个数来决定底部内容区的个数*/
let blen = this.props.bottomValue.topValue.length;
for(var i=0;i<blen;i++){
bDiv.push(<div className='con' key={i} style={{display:this.props.bIndex==i?'block':'none'}}>{this.props.bottomValue.bottomValue[i]}</div>);
}
return (
<div>{bDiv}</div>
);
}
}
/*定义tab组件*/
class Tab extends React.Component{
constructor(){
super();
/*定义一个状态存储下标值*/
this.state = {
index:0,
timer: null
}
}
change(i){
this.setState({
index:i
});
}
/*自动播放效果*/
auto(){
/*先清除定时器,再添加*/
clearInterval(this.timer);
this.timer = setInterval(()=>{
let index = this.state.index;
index++;
if(index == this.props.myData.topValue.length){
index = 0;
}
this.setState({
index:index
});
},this.props.myData.time);
}
/*组件挂载后自动播放*/
componentDidMount(){
this.auto();
}
/*鼠标移入停止播放*/
mouseOverFn(){
clearInterval(this.timer);
}
/*鼠标离开恢复播放*/
mouseLeaveFn(){
this.auto();
}
render(){
return (
<div onMouseOver={this.mouseOverFn.bind(this)} onMouseLeave={this.mouseLeaveFn.bind(this)}>
<Top topValue={this.props.myData.topValue} tChange={this.change.bind(this)} tIndex={this.state.index}/>
<Bottom bottomValue={this.props.myData} bIndex={this.state.index}/>
</div>
)
}
}
ReactDOM.render(
<Tab myData={{topValue:['中国','美国','加拿大'],bottomValue:['这个国家很强','这个国家有钱','这个国家很美'],time:500}}/>,
document.getElementById('example')
);
</script>
</body>
</html>
react ---选项卡
猜你喜欢
转载自blog.csdn.net/hahahahahahahaha__1/article/details/80725320
今日推荐
周排行