如何使用 Waypoint 获取活动元素?

How do you get the active element using Waypoint?

我在 React (16) 中使用 Waypoint (7.3.2) 来尝试创建一个可滚动项目列表,其中每个项目在到达 div 顶部时逐渐消失。我的基本问题是如何获取对 enters/leaves 事件或回调中的路径点的元素的引用?

我认为通过在元素中包含 ref={} 我想在回调中获得元素的引用并能够更改不透明度。下面是插入Waypoint的代码:

class Division extends Component {
    constructor(props) {
        super(props);
    }

    _handleWayPointEnter = (event) => {
        console.log("Waypoint enter " + JSON.stringify(event, 4));
    }
    _handleWayPointLeave = (event) => {
        console.log("Waypoint leave " + JSON.stringify(event, 4));
    }

    render() {
        let inlineStyle= {opacity : this.state.opacity};
        return (
            <Waypoint debug={false} onEnter={this._handleWayPointEnter} onLeave={this._handleWayPointLeave} >
                <div style={inlineStyle} ref={this.props.innerRef} className="sch-division">
                    {this.props.name}<br/>
                    <SomeOtherComponent />
                </div>
            </Waypoint>
        );
    }

}

export default Division;

Any/all回帖感激不尽!

-- 格里夫

来自 react-waypoint 文档:

If you do pass a child, it can be a single DOM component (e.g. <div>) or a composite component (e.g. <MyComponent />).

Waypoint needs a DOM node to compute its boundaries. When you pass a DOM component to Waypoint, it handles getting a reference to the DOM node through the ref prop automatically. If you pass a composite component, you need to make use of the innerRef prop passed by Waypoint to your component. Simply pass it through as the ref of a DOM component and you're all set. Like in this example:

class Block extends React.Component {
  render() {
    return <div ref={this.props.innerRef}>Hello</div>
  }
}
Block.propTypes = {
  innerRef: PropTypes.func.isRequired,
}

const App = () => (
  <Waypoint>
    <Block />
  </Waypoint>
)

这里您使用的是单个 DOM 组件 (<div>),我建议您像这样存储 div ref :

<div style={inlineStyle} ref={(div) => { this.divinwaypoint = div; }} className="sch-division">

然后在你的函数中使用它:

_handleWayPointEnter = (event) => {
   console.log("Waypoint enter " + JSON.stringify(event, 4));
   this.divinwaypoint.style.opacity = 0;
}

编辑:我没有使用航路点,但我认为它应该在 event 道具中显示您的组件参考。