首页 > 解决方案 > React.js 中这三种语法有什么区别?

问题描述

我是反应新手。它可能比 React 问题更多的是 JS 问题。当我为此部分以三种不同的方式编写代码时,它们都可以正常工作,在控制台中显示“ID 为 1”。

1

<Post click={() => this.postSelectedHandler(post.id)}/>

2

<Post click={() => {this.postSelectedHandler(post.id)}}/>

3

<Post click={() => {return this.postSelectedHandler(post.id)}}/>

我的问题是为什么它们都工作正常。特别是#3 返回函数,我不明白为什么它的工作方式与其他两个相同。关于 #1 和 #2,有无 {} 都无所谓?

原始代码(与#1 相同)

  postSelectedHandler = id => {
    console.log("ID is " + id);
  };

  render() {
    const posts = this.state.posts.map(post => {
      return (
        <Post click={() => this.postSelectedHandler(post.id)}/>
      );
    });

    
    return (
      <div>
        <section>{posts}</section>
      </div>
    );
  }

谢谢您的帮助。

标签: javascriptreactjssyntaxarrow-functions

解决方案


推荐阅读