javascript - react , "this",cloneElement 和 es6

标签 javascript reactjs ecmascript-6

我想知道当您将 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>
    )
  }
});

然后在它的 child 中:

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

最佳答案

autobinding React.createClass 确实包含 was removed对于 ES6 类(另见 this article)。所以你现在必须手动完成:

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

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

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

关于javascript - react , "this",cloneElement 和 es6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31841949/

相关文章:

javascript - 回发后在 TextBox 中设置焦点

Javascript - 如何创建元素,将其添加到数组中并显示它

javascript - MongoDB 聚合 $lookup $match

reactjs - 如何提取 "=>"到函数模型

javascript - 有没有办法增加material-ui中轮廓按钮的边框厚度?

javascript - 如何在本地主机上执行React D3组件

javascript - create-react-app webpack 配置和文件在哪里?

javascript - 如何访问在类的方法中声明的变量?

javascript - 问题在 angular5 中添加第三方(外部)js 库

javascript - 转换 reduce 函数以与 IE 一起使用