UNPKG

2.54 kBJavaScriptView Raw
1import React, { Component } from 'react';
2import ReactDOM from 'react-dom';
3import PropTypes from 'prop-types';
4import Gumshoe from 'gumshoejs';
5
6const propTypes = {
7 selector:PropTypes.string.isRequired,//选择器
8 offset:PropTypes.func,//偏移量
9 navClass:PropTypes.string,//当前被激活锚点新增的类名
10 contentClass:PropTypes.string,//当前被激活的区域
11 nested:PropTypes.bool,
12 nestedClass:PropTypes.string,
13 reflow:PropTypes.bool,
14 event:PropTypes.bool,//是否添加监听事件
15 activeHandle:PropTypes.func,//被激活的回调
16 deactiveHandle:PropTypes.func,//激活后的回调
17};
18const defaultProps = {
19 navClass: 'active', // applied to the nav list item
20 contentClass: 'active', // applied to the content
21
22 // Nested navigation
23 nested: false, // if true, add classes to parents of active link
24 nestedClass: 'active', // applied to the parent items
25
26 // Offset & reflow
27 offset: 0, // how far from the top of the page to activate a content area
28 reflow: false, // if true, listen for reflows
29
30 // Event support
31 events: true, // if true, emit custom events
32 activeHandle:()=>{},
33 deactiveHandle:()=>{}
34};
35class Anchor extends Component {
36
37 componentDidMount(){
38 let props = this.props;
39 this.anchor = new Gumshoe(props.selector,{
40 ...props
41 })
42 this.anchorDOM.addEventListener('gumshoeActivate',(event)=>{
43 // The list item
44 let li = event.target;//列表
45
46 // The link
47 let link = event.detail.link;//a标签
48
49 // The content
50 let content = event.detail.content;//内容区域
51
52 props.activeHandle(li,link,content)
53 })
54 this.anchorDOM.addEventListener('gumshoeDeactivate',(event)=>{
55 let li = event.target;//列表
56
57 // The link
58 let link = event.detail.link;//a标签
59
60 // The content
61 let content = event.detail.content;//内容区域
62
63 props.deactiveHandle(li,link,content)
64 })
65 }
66 componentDidUpdate(){
67 this.anchor.setup()
68 this.anchor.detect()
69 }
70 componentWillUnmount(){
71 this.anchor.destroy()
72 }
73 render(){
74 return (
75 <div className='u-anchor' ref={ref=>{this.anchorDOM=ref}}>
76 {this.props.children}
77 </div>
78 )
79 }
80};
81
82Anchor.propTypes = propTypes;
83Anchor.defaultProps = defaultProps;
84export default Anchor;
\No newline at end of file