小编典典

反应“ this”,cloneElement和es6

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>
    )
  }
});

然后在其子节点中:

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(){...}
};

阅读 215

收藏
2020-07-22

共1个答案

小编典典

ES6类已删除具有React.createClass功能的自动绑定(另请参阅本文)。因此,您现在必须手动进行操作:

…
  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
      });
    );
  }
  …
}
2020-07-22