您可以通过几种不同的方法来执行此操作。一种是通过组合:
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弃用?您可以阅读有关此内容的内容,然后自己决定自己的想法。



