gpt4 book ai didi

javascript - 如何使用 Waypoint 获取事件元素?

转载 作者:可可西里 更新时间:2023-11-01 13:21:16 26 4
gpt4 key购买 nike

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

我认为通过在元素中包含 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;

感谢任何/所有回复!

-- 格里夫

最佳答案

来自 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 引用:

<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 中显示您的组件引用 Prop 。

关于javascript - 如何使用 Waypoint 获取事件元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47677099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com