在 React 中将函数作为带括号或不带括号的 prop 传递有什么区别?

YSA*_*YSA 1 reactjs redux material-ui react-redux

这可能是我应该知道的,但是当我传递不带括号的函数时,我不太了解组件的行为。这是我的组件代码。

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';

import AppBar from 'material-ui/AppBar';
import LoginButton from './LoginButton';
import LogoutButton from './LogoutButton';

class Header extends Component {
  renderButton() {
    switch (this.props.auth) {
      case null:
        return
      case false:
        return <LoginButton />
      default:
        return <LogoutButton />
    }
  }



handleTitleClick() {
    return(
      <Link to={this.props.auth ? '/classes' : '/'}>
        QueueMe
      </Link>
    );
  }

  render() {
    const styles = {
      title: {
        cursor: 'pointer',
      },
    };

    return(
      <AppBar
        title={<span style={styles.title}>QueueMe</span>}
        onTitleClick={this.handleTitleClick()}
        iconElementRight={this.renderButton()}
        showMenuIconButton={false}
      />
    );
  }
}

/*
 * @input: redux state
 * Allows the component to access certain piece of the state as props
 * Reducers determine the key in the state
 */
function mapStateToProps(state) {
  return { auth: state.auth };
}

export default connect(mapStateToProps)(Header);
Run Code Online (Sandbox Code Playgroud)

对于我在 中的onTitleClick属性<AppBar>,当我传递它handleTitleClick()时我得到了预期的行为,但是当我传递它handleTitleClick并单击它时,我收到一个错误消息,显示Cannot read property 'auth' of undefined. 这里究竟有什么区别导致handleTitleClick不知道状态?

Joh*_*efs 5

好问题!这里发生了一些错误。Javascriptthis可能是一个真正的痛苦。问题是你的函数没有绑定。

当您编写时,onTitleClick={this.handleTitleClick()}您会在编译时立即调用该函数。当您handleTitleClick在提供未绑定函数时传递它时,它没有this定义。

有两种可能的解决方案,您可以定义

handleTitleClick = (event) =>
    return(
      <Link to={this.props.auth ? '/classes' : '/'}>
        QueueMe
      </Link>
    );
  }
Run Code Online (Sandbox Code Playgroud)

这使得 handleTitleClick 成为一个箭头函数,箭头函数将它们绑定this到创建它们的闭包。

如果你不喜欢使用 IIFE 方式,你可以随时使用

constructor(props) {
   super(props)
   this.handleTitleClick = this.handleTitleClick.bind(this)
}
Run Code Online (Sandbox Code Playgroud)

如果您仍然卡住,请检查一下。 https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56