Understanding trasferPropsTo

Understanding trasferPropsTo

本文关键字:trasferPropsTo Understanding      更新时间:2023-09-26

我看不出transferPropsTo是for,看文档

给出的示例如下:

var Avatar = React.createClass({
  render: function() {
    return this.transferPropsTo(
      <img src={"/avatars/" + this.props.userId + ".png"} userId={null} />
    );
  }
});
// <Avatar userId={17} width={200} height={200} />

我看不出这和:

有什么区别
return (
    <img src={"/avatars/" + this.props.userId + ".png"} />
)

还有什么我不明白的:

  • userId={null}应该说明什么?
  • <Avatar />通过width=height=。对什么?他们会怎么样?

transferPropsTo方法用于将属性从一个对象复制到另一个对象,文档试图准确地解释哪些属性被复制。

userId={null}应该说明什么?

显式设置不会被transferPropsTo覆盖,因此它显示即使userIdAvatar上设置,也不会被复制,因为userIdimg上显式设置为null。

传递给Avatar一个width=和height=。对什么?他们会怎么样?

这两个属性被"转移"到img,所以这个例子大致相当于:

return (
    <img src={"/avatars/" + this.props.userId + ".png"} // explicit
         userId={null}                        // explicit, not overwritten
         width={this.props.width}             // copied
         height={this.props.height}           // copied
         />
)

与原始示例的区别在于,构建Avatar的代码控制img上设置的附加属性,而不是Avatar的呈现方法本身。