【问题标题】:When to use anonymous functions in JSX何时在 JSX 中使用匿名函数
【发布时间】:2017-07-08 10:23:48
【问题描述】:

谁能解释一下

一个匿名函数

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

如下调用函数

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

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

【问题讨论】:

    标签: reactjs react-jsx jsx


    【解决方案1】:

    第一个示例正确绑定了this 的值(正是 lambdas 努力在 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

    【讨论】:

      【解决方案2】:

      ES6中,第一种情况“this”指的是被调用函数所属的Component。 &lt;button onClick={() =&gt; this.functionNameHere()}&gt;&lt;/button&gt; 等价于&lt;button onClick={this.functionNameHere.bind(this)}&gt;&lt;/button&gt;

      另一方面,在&lt;button onClick={this.functionNameHere()}&gt;&lt;/button&gt; 中,“this”指的是按钮本身。

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

      【讨论】:

      • 如果在第二个例子中 this 指的是按钮本身。当页面重新渲染时,为什么无论如何都会调用该函数?既然函数被定义为类函数而不是按钮函数,那么 this.functionNameHere() 不应该是未定义的吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 2019-04-04
      • 1970-01-01
      • 2014-08-16
      相关资源
      最近更新 更多