javascript - 理解transferPropsTo

标签 javascript reactjs

我看不懂 transferPropsTo是为了,阅读 the docs .

给出的示例如下所示:

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 方法用于将属性从一个对象复制到另一个对象,文档试图准确解释复制了哪些属性。

what's the userId={null} supposed to illustrate?

显式进行的设置不会被 transferPropsTo 覆盖,因此它表明,即使 userId 是在 Avatar 上设置的,由于 img 上的 userId 被显式设置为 null,因此不会被复制。

Avatar is passed a width= and height=. What for? What happens to them?

这些是“转移”到 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 的渲染方法本身。

关于javascript - 理解transferPropsTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23732826/

相关文章:

css - FlatList 之前的元素固定在页面上,不会随 FlatList 滚动

node.js - 无法从本地主机获取数据

javascript - React 从本地存储导入图像

javascript - 什么时候使用 JSX.Element vs ReactNode vs ReactElement?

javascript - Fadein() 对函数的效果 : how to?

javascript - 如何使用按钮从外部激活导航选项卡?

javascript - 为什么原型(prototype)在简单的 JavaScript 对象中不可用

javascript - jQuery Loudev 多重选择不起作用

javascript - 从返回的猫​​鼬文档实例中删除属性。 MongoDB

reactjs - 如何在 react 谷歌地图中旋转标记图标(svg图像)