作者:可爱的伊比2324767445hMkK | 来源:互联网 | 2022-12-10 07:50
考虑到React 16的Context API,我已经看了两个可能过时的答案。
他们是:
React.js关于侦听组件窗口事件的最佳实践
和:
如何在React中实现类似于service(AngularJS中的concept)的组件
我对React 还是很陌生,所以我想知道,鉴于Context API,这是在React中进行Angular.js类型服务的正确方法(因此我没有window.addEventListener("scroll")
在每个组件上监听滚动事件) ,以利用Context API(在此处创建事件侦听器?),只是想知道我是否在这里正确无误...
它讨论了能够传递道具,还涉及了嵌套组件能够改变状态,让包装器组件收集滚动位置,更新Context(滚动位置)并将其传递给需要的元素?有没有推荐的方法来做到这一点,window.addEventListener("scroll")
甚至有很多问题吗?
创建嵌套组件后,我很难理解如何从其更新上下文-在此处的文档中:https : //reactjs.org/docs/context.html#updating-context-from-a-nested-component
因此,我不确定要从顶级/父元素更新上下文并将其传递给内部组件。
1> Ori Drori..:
您可以使用上下文API创建带有HoC的Provider 。每当窗口大小更改时,提供者都会通过更新宽度/高度来通知消费者,而HoC中的消费者会重新渲染组件。
例:
const getDimensiOns= () => ({
width: window.innerWidth,
height: window.innerHeight
});
const ResizeCOntext= React.createContext(getDimensions());
class ResizeProvider extends React.PureComponent {
state = getDimensions();
// you might want to debounce or throttle the event listener
eventListener = () => this.setState(getDimensions());
componentDidMount() {
window.addEventListener('resize', this.eventListener);
}
componentWillUnmount() {
window.removeEventListener('resize', this.eventListener);
}
render() {
return (
{
this.props.children
}
);
}
}
const withResize = (Component) => (props) => (
{({ width, height }) => (
)}
);
const ShowSize = withResize(({ width, height }) => (
Width: {width}
Height: {height}
));
const Demo = () => (
);
ReactDOM.render(
,
demo
);