React、“this”、cloneElement 和 es6

IT技术 javascript reactjs ecmascript-6
2021-04-14 20:18:49

我想知道当你传递一个函数时 ES6 和 cloneElement 是如何工作的。我需要在父组件的状态中this引用状态,但引用子组件而不是父组件。

下面是常规 JavaScript 中的代码,使其工作,在第一次用 ES6 编写它并将我的头敲在键盘上之后,我决定看看它是否是 ES6,所以我重构了它,它工作得很好。

我只想用 ES6 编写它,因为其他一切都是如此,但这让我很难过。

这是我在 ES5 中的组件:

var Parent = React.createClass({
  content: function() {
    return React.Children.map(this.props.children, function(child) {
     return React.cloneElement(child, {
       passThisFunc: this.passThisFunc
     })
    }.bind(this));
  },

  passthisfunc: function(component) {
    // returns the components props
    console.log(this);

    // Returns the component so I can do component.props.name
    console.log(component);
  },

  render: function() {
    return (
      <div>
        { this.content }
      </div>
    )
  }
});

然后在它的孩子中:

var Child = React.createClass({
  componentDidMount: function() {
    this.props.passThisFunc(this);
  }

  render: function().....
});

ES6 中的组件没有什么不同,它实际上this是记录时引用的内容。

任何重构(尤其是父组件)的帮助将不胜感激。

编辑 这是我尝试过的 ES6 示例:

class Parent extends React.Component {
  content() {
    return React.Children.map(this.props.children, function(child) {
     return React.cloneElement(child, {
       passThisFunc: this.passThisFunc
     })
    }.bind(this));
  }

  passthisfunc(component) {
    // returns the components props
    console.log(this);

    // Returns the component so I can do component.props.name
    console.log(component);
  }

  render() {
    return (
      <div>
        { this.content }
      </div>
    )
  }
};

class Child extends React.Component {
  componentDidMount() {
    this.props.passThisFunc(this);
  }

  render(){...}
};
1个回答

自动绑定React.createClass做功能移除了ES6类(见本文)。所以你现在必须手动完成:

…
  content: function() {
    return React.Children.map(this.props.children, function(child) {
     return React.cloneElement(child, {
       passThisFunc: this.passThisFunc.bind(this)
     })
    }.bind(this));
  },
…

但是在 ES6 中你不会真的这样做。相反,您首先会使用箭头函数,它具有词法this绑定:

class Parent extends React.Component {
  constructor() {
    super();
    this.passthisfunc = (component) => {
      // returns the parent
      console.log(this);

      // Returns the component so I can do component.props.name
      console.log(component);
    };
  }
  content() {
    return React.Children.map(this.props.children, child =>
      React.cloneElement(child, {
        passThisFunc: this.passThisFunc
      });
    );
  }
  …
}
注意:箭头函数在每次渲染时都会重新创建函数——这是一个微性能命中,需要权衡更清晰的语法。
2021-05-29 20:18:49
@AshleyCoolman 只有在内部声明render(或由它调用的方法)时,我还没有做过 afaik
2021-06-17 20:18:49