javascript - ReactJS prop 绑定(bind)是如何工作的?

标签 javascript reactjs

下面的值 ( <ArticleList instance>.props.articles ) 绑定(bind)到 HomePage 的 prop (this.props.articles)。

this.props.articles的对象标识可能是undefined或者它可能会改变,因此 ReactJS 必须将“this.props.articles”维护为配置而不是对象引用,从而允许动态查找。

这是正确的吗?

class HomePage extends React.PureComponent {
  render() {
    return <ArticleList articles={this.props.articles} />
  }
}

function ArticleList({articles}) { 
  if(!articles) return <div>There are no articles!</div>;
  return <div>{ articles.map(a => <Article value={a} />) }</div>;
}

编辑:我已编辑代码以涵盖 undefined 的情况。我的问题仍然存在。

重申:

this.props.articles看起来像一个用于检索属性值的 JavaScript 表达式。

但这不可能是由于问题中所述的原因(您将绑定(bind)未定义)。

那么这是 JSX 知道如何解析的特殊 JSX 语法吗?

最佳答案

为什么说 this.props.articles 不是 JavaScript?

你的代码一旦被 Babel 转译就会变成:

class HomePage extends React.PureComponent {
  render() {
    return React.createElement(ArticleList, {
      articles: this.props.articles,
    });
  }
}

function ArticleList({articles}) { 
  if(!articles) {
    return React.createElement('div', {}, 'There are no articles!');
  }
  return React.createElement('div', {},
    articles.map(a => <Article value={a} />)
  );
}

this.props.articles 只是对 HomePage 类的 props 属性的引用。

关于javascript - ReactJS prop 绑定(bind)是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45209867/

相关文章:

javascript - 根据其键聚焦特定元素

javascript - JavaScript 仪表的奇怪效果

javascript - 文本节点添加事件监听器

javascript - 如何为 'mailto' 建立 Gatsby 链接?

javascript - 在元素上启动动画的捕获函数

Javascript/React - 不重复自己的最佳方式

javascript - React-native,在 android 上使用全屏图像

javascript - 样式/更改 Material UI React 中的自动完成关闭图标

reactjs - 如何避免 useMemo 过度使用?

node.js - 使用 Create React App 进行两种方式的值更改