何时在 JSX 中使用匿名函数

IT技术 reactjs react-jsx jsx
2021-05-26 00:53:55

有人可以解释两者之间的区别吗

匿名函数

  <button onClick={() => this.functionNameHere()}></button>

调用如下函数

  <button onClick={this.functionNameHere()}></button>

以及何时使用其中之一(例如在不同的场景中使用一个而不是另一个)。

2个回答

第一个示例正确绑定了的值this(Lambda 在 ES 2015 中力求解决的确切问题)。

 () => this.functionNameHere()

后者使用this可能不是您期望的范围值例如:

export default class Album extends React.Component {

    constructor(props) {
        super(props);
    }

    componentDidMount ()  {
        console.log(this.props.route.appState.tracks);  // `this` is working
        axios({
            method: 'get',
            url: '/api/album/' + this.props.params.id + '/' + 'tracks/',
            headers: {
                'Authorization': 'JWT ' + sessionStorage.getItem('token')
            }
        }).then(function (response) {
            console.log(response.data);
            this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
        }).catch(function (response) {
            console.error(response);
            //sweetAlert("Oops!", response.data, "error");
        })
    }

我们需要在此处添加一个 lambda:

.then( (response) => {
        console.log(response.data);
        this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
    } )

或手动绑定:

.then(function (response) {
            console.log(response.data);
            this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
        }.bind(this) )

示例来自:React this is undefined

ES6 中,第一个场景“this”指的是被调用函数所属的组件。<button onClick={() => this.functionNameHere()}></button>相当于<button onClick={this.functionNameHere.bind(this)}></button>

另一方面,在<button onClick={this.functionNameHere()}></button>“this”中是指按钮本身。

我来自 Python,但我仍然对 javascript 上下文有些困惑。查看此视频了解更多信息:https : //www.youtube.com/watch?v=SBwoFkRjZvE&index=4&list=PLoYCgNOIyGABI011EYc-avPOsk1YsMUe_