Browse Source

Improve code for #2247

pull/2452/head
afc163 8 years ago
parent
commit
4ac775212f
  1. 7
      components/affix/demo/on-change.md
  2. 49
      components/affix/index.jsx
  3. 1
      package.json

7
components/affix/demo/on-change.md

@ -8,13 +8,8 @@ title: 固定状态改变的回调
````jsx
import { Affix, Button } from 'antd';
const onChange = function (affixed) {
console.log(affixed); // true or false
};
ReactDOM.render(
<Affix offsetTop={120} onChange={onChange}>
<Affix offsetTop={120} onChange={affixed => console.log(affixed)}>
<Button>固定在距离顶部 120px 的位置</Button>
</Affix>
, mountNode);

49
components/affix/index.jsx

@ -3,6 +3,7 @@ import ReactDOM from 'react-dom';
import addEventListener from 'rc-util/lib/Dom/addEventListener';
import classNames from 'classnames';
import warning from 'warning';
import shallowequal from 'shallowequal';
function getScroll(w, top) {
let ret = w[`page${top ? 'Y' : 'X'}Offset`];
@ -50,6 +51,20 @@ export default class Affix extends React.Component {
};
}
setAffixStyle(affixStyle) {
const originalAffixStyle = this.state.affixStyle;
if (shallowequal(affixStyle, originalAffixStyle)) {
return;
}
this.setState({ affixStyle }, () => {
const affixed = !!this.state.affixStyle;
if ((affixStyle && !originalAffixStyle) ||
(!affixStyle && originalAffixStyle)) {
this.props.onChange(affixed);
}
});
}
handleScroll = () => {
let { offsetTop, offsetBottom, offset } = this.props;
@ -73,29 +88,23 @@ export default class Affix extends React.Component {
if (scrollTop > elemOffset.top - offsetTop && offsetMode.top) {
// Fixed Top
this.setState({
affixStyle: {
position: 'fixed',
top: offsetTop,
left: elemOffset.left,
width: ReactDOM.findDOMNode(this).offsetWidth,
},
}, () => { if (!this.state.affixStyle) this.props.onChange(!!this.state.affixStyle) });
this.setAffixStyle({
position: 'fixed',
top: offsetTop,
left: elemOffset.left,
width: ReactDOM.findDOMNode(this).offsetWidth,
});
} else if (scrollTop < elemOffset.top + elemSize.height + offsetBottom - window.innerHeight &&
offsetMode.bottom) {
// Fixed Bottom
this.setState({
affixStyle: {
position: 'fixed',
bottom: offsetBottom,
left: elemOffset.left,
width: ReactDOM.findDOMNode(this).offsetWidth,
},
}, () => { if (!this.state.affixStyle) this.props.onChange(!!this.state.affixStyle) });
} else if (this.state.affixStyle) {
this.setState({
affixStyle: null,
}, () => this.props.onChange(!!this.state.affixStyle));
this.setAffixStyle({
position: 'fixed',
bottom: offsetBottom,
left: elemOffset.left,
width: ReactDOM.findDOMNode(this).offsetWidth,
});
} else {
this.setAffixStyle(null);
}
}

1
package.json

@ -70,6 +70,7 @@
"rc-util": "~3.1.0",
"react-addons-pure-render-mixin": "^15.0.0",
"react-slick": "~0.12.0",
"shallowequal": "^0.2.2",
"warning": "~3.0.0"
},
"devDependencies": {

Loading…
Cancel
Save