请使用高阶组件而不是Mixin

优质
小牛编辑
135浏览
2023-12-01

简单的例子

  1. // 使用mixin
  2. var WithLink = React.createClass({
  3. mixins: [React.addons.LinkedStateMixin],
  4. getInitialState: function () {
  5. return {message: 'Hello!'};
  6. },
  7. render: function () {
  8. return <input type="text" valueLink={this.linkState('message')}/>;
  9. }
  10. });
  11. // 使用高阶组件的做法
  12. var WithLink = React.createClass({
  13. getInitialState: function () {
  14. return {message: 'Hello!'};
  15. },
  16. render: function () {
  17. return <input type="text" valueLink={LinkState(this,'message')}/>;
  18. }
  19. });

更加详细的例子

  1. // 使用Mixin Mixin
  2. var CarDataMixin = {
  3. componentDidMount: {
  4. // fetch car data and
  5. // call this.setState({carData: fetchedData}),
  6. // once data has been (asynchronously) fetched
  7. }
  8. };
  9. var FirstView = React.createClass({
  10. mixins: [CarDataMixin],
  11. render: function () {
  12. return (
  13. <div>
  14. <AvgSellingPricesByYear country="US" dataset={this.state.carData}/>
  15. <AvgSellingPricesByYear country="UK" dataset={this.state.carData}/>
  16. <AvgSellingPricesByYear country="FI" dataset={this.state.carData}/>
  17. </div>
  18. )
  19. }
  20. });
  21. // 使用高阶组件
  22. var bindToCarData = function (Component) {
  23. return React.createClass({
  24. componentDidMount: {
  25. // fetch car data and
  26. // call this.setState({carData: fetchedData}),
  27. // once data has been (asynchronously) fetched
  28. },
  29. render: function () {
  30. return <Component carData={ this.state.carData }/>
  31. }
  32. });
  33. };
  34. // 将你的组件使用高阶组件包裹起来
  35. var FirstView = bindToCarData(React.createClass({
  36. render: function () {
  37. return (
  38. <div>
  39. <AvgSellingPricesByYear country="US" dataset={this.props.carData}/>
  40. <AvgSellingPricesByYear country="UK" dataset={this.props.carData}/>
  41. <AvgSellingPricesByYear country="FI" dataset={this.props.carData}/>
  42. </div>
  43. )
  44. }
  45. }));

参考资料: