React,"this",cloneElement和es6

Ril*_*ken 8 javascript ecmascript-6 reactjs

我想知道当你传递一个函数时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>
    )
  }
});
Run Code Online (Sandbox Code Playgroud)

然后在它的孩子们:

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

  render: function().....
});
Run Code Online (Sandbox Code Playgroud)

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(){...}
};
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 16

自动绑定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));
  },
…
Run Code Online (Sandbox Code Playgroud)

但你不会在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
      });
    );
  }
  …
}
Run Code Online (Sandbox Code Playgroud)