小编典典

React.js关于侦听组件窗口事件的最佳实践

reactjs

我正在根据其在视口中的位置为几个React.js组件设置动画。如果组件中视,动画不透明度为1,如果不是在视口中,有生其不透明度为0。我使用getBoundingClient()topbottom属性,以确定该组件是视域之内。

ComponentA显示了我遵循的其他B,C和D组件的模式。他们每个人都在监听window滚动事件。

这是每个组件都必须向事件添加事件侦听器的“反应”方式window吗?同一窗口上有多个滚动事件侦听器?

还是通过在Home所有者组件处将滚动事件侦听器添加到窗口中来更好的方法?那么,所有者子组件仍然可以使用来知道它们在DOM中的位置getBoundingClient()吗?

Home = React.createClass({
 render: function() {
    <div>
       <ComponentA />
       <ComponentB />
       <ComponentC />
       <ComponentD />
    </div>
  };
});

ComponentA = React.createClass({
  componentDidMount: function() {
   window.addEventListener('scroll', this.handleScroll);
},
  componentWillUnmount: function() {
    window.removeEventListener('scroll', this.handleScroll);
   },

handleScroll: function() {
  var domElement = this.refs.domElement.getDOMNode();
  this.inViewPort(domElement);
},

inViewPort: function(element) {
  var elementBounds = element.getBoundingClientRect();
  (elementBounds.top <= 769 && elementBounds.bottom >= 430) ? TweenMax.to(element, 1.5, { opacity: 1 }) : TweenMax.to(element, 1.5, { opacity: 0 });
},
render: function() {
  return (/* html to render */);
 }

});

阅读 244

收藏
2020-07-22

共1个答案

小编典典

您可以通过几种不同的方法来执行此操作。一种是通过组合:

var React = require("react");
var _ = require("underscore");

var ScrollWrapper = React.createClass({
    propTypes: {
        onWindowScroll: React.PropTypes.func
    },

    handleScroll: function(event) {
        // Do something generic, if you have to
        console.log("ScrollWrapper's handleScroll");

        // Call the passed-in prop
        if (this.props.onWindowScroll) this.props.onWindowScroll(event);
    },

    render: function () {
        return this.props.children;
    },

    componentDidMount: function() {
        if (this.props.onWindowScroll) window.addEventListener("scroll", this.handleScroll);
    },

    componentWillUnmount: function() {
        if (this.props.onWindowScroll) window.removeEventListener("scroll", this.handleScroll);
    }
});

var ComponentA = React.createClass({
    handleScroll: function(event) {
        console.log("ComponentA's handleScroll");
    },

    render: function() {
        return (
            <ScrollWrapper onWindowScroll={this.handleScroll}>
                <div>whatever</div>
            </ScrollWrapper>
        );
    }
});

现在,您可以将通用逻辑放置在ScrollWrapper组件中,然后突然变得可重用。您可以创建一个ComponentB用来渲染ScrollWrapper就像ComponentA做。

为了满足您的示例,也许您必须从​​中传递ScrollWrapper一些额外的道具ComponentA。也许您将传递给它一个道具,其中包含的实例ref以调用您的逻辑。您甚至可以向其传递一些选项或参数以自定义补间或边界。我没有编写任何代码,因为我想您会理解它并能够使用我提供的基础自己定制/编写。

实现此类目标的另一种方法是通过Mixin。虽然,有很多关于Mixins是好是坏的讨论,并且它们甚至将来可能被React弃用?您可以阅读有关此内容的内容,然后自己决定自己的想法。

2020-07-22