【问题标题】:Calling a function in React在 React 中调用函数
【发布时间】:2017-12-19 08:45:23
【问题描述】:

我是 React 的初学者,对于在 React 中调用函数有点困惑。

我看到了以下几种方式,不知道什么时候用,哪一种。

  • handleAddTodo ={this.handleAddTodo}
  • handleAddTodo ={this.handleAddTodo()}
  • handleAddTodo ={handleAddTodo}
  • handleAddTodo ={this.handleAddTodo}
  • handleAddTodo ={handleAddTodo()}

这些可以互换吗?我可以这样做来处理事件,就像调用函数一样吗?

【问题讨论】:

  • 你想从其他组件触发事件吗?
  • 您确定要调用一个函数而不将其作为子组件的属性传递吗?
  • @YuryTarabanko :是的,我传递了一个函数调用,这是一个孩子的道具,传递一个函数不是隐含地认为是调用它吗?
  • @AnynameDonotcare “没有传递一个隐式认为调用它的函数” 不。您要么传递一个函数(以便您的子组件可以稍后调用它,也就是“回调”),要么调用它并传递它返回的结果。

标签: javascript reactjs jsx dom-events


【解决方案1】:

这些可以互换吗?

简短回答:不。


让我们看看你发布的不同的sn-ps:


someFunction()someFunction

使用前一种语法,您实际上是在调用该函数。后者只是对该函数的引用。那么我们什么时候用哪个呢?

  • 当您希望调用该函数并立即返回其结果时,您可以使用someFunction()。在 React 中,当您将 JSX 代码的一部分拆分为单独的函数时,通常会看到这种情况;出于可读性或可重用性的原因。例如:

    render() {
      myFunction() {
        return <p>Foo Bar</p>;
      }
      return (
        <div>
          {myFunction()}
        </div>
      );
    }
    

  • 当您只想将对该函数的引用传递给其他东西时,您可以使用someFunction。在 React 中,这通常是一个事件处理程序,它通过props 传递给另一个子组件,以便该组件可以在需要时调用事件处理程序。例如:

    class myApp extends React.Component {
      doSomething() {
        console.log("button clicked!");
      }
      render() {
        return (
          <div>
            <Button someFunction={this.doSomething} />
          </div>
        );
      }
    }
    
    class Button extends React.Component {
      render() {
        return (
          <button onClick={this.props.someFunction}>Click me</button>
        );
      }
    }
    

someFunction()this.someFunction()

这与函数的上下文有关。基本上,“这个功能在哪里?”。是当前Component的一部分,则使用this.someFunction(),是否是作为props传入的父Component的一部分,则使用this.props.someFunction()。是不是当前方法里面的一个函数,那么就用someFunction()吧。

显然,它的意义远不止于此,但这是我能给出的最好的基本总结。

为了更好地理解,请阅读here。它是关于 this 关键字如何在 Javascript 尤其是 React 中工作的一个很好的指南。

【讨论】:

    【解决方案2】:

    如果您想调用一个函数,选项 2 和一些假设 5 应该可以工作。

    如果你想真正传递一个函数作为一个属性到某个子组件,以便它可以稍后调用它(比如在某个事件上通知你的根元素),那么选项 1(带有预绑定)和 3(定义变量 const {handleAddTodo} = this 和 prebind :))应该可以工作

    // this works if handleAddTodo was prebinded or doesn't use this
    handleAddTodo ={this.handleAddTodo} 
    
    // this probably wont work unless handleAddTodo is higher order function that returns another function
    handleAddTodo ={this.handleAddTodo()} 
    
    // This wont work unless you have a var/let/const that is referencing a function
    handleAddTodo ={handleAddTodo} 
    
    // Same as 1
    handleAddTodo ={this.handleAddTodo} 
    
    // 3 and 2 combined
    handleAddTodo ={handleAddTodo()} 
    

    【讨论】:

      【解决方案3】:

      要调用函数,您必须添加 ()

      {this.handleAddTodo()}   
      

      关于处理事件 - Handling#Events

      箭头函数 - Functions#ArrowFunctions

      【讨论】:

        【解决方案4】:

        在 ES6 中你可以使用普通函数或箭头函数:

        Function1(正规函数)

        functionA(){
           //Something here
        }
        

        然后应该调用 this.functionA()

        Function2(ArrowFunction)

        functionA = () => {
           //SomeThing Here
        }
        

        然后应该调用 this.functionA

        *Function3(例如:在 React 的 const 中)*

        const A = (functionTest) =>{
          return (
             <div>{functionTest}</div>
            );
        }
        

        functionTest 是 React 中的 mapStateToProps :)

        希望对你有帮助:)

        【讨论】:

          【解决方案5】:

          这是正确的 -> handleAddTodo ={this.handleAddTodo} 当函数传递给子组件时,您必须像 handleAddTodo ={this.handleAddTodo.bind(this)} 那样绑定您的函数。下面的代码可以帮助您解决疑问。

          简单示例

          import React from 'react';
          
          class App extends React.Component {
          
             constructor(props) {
                super(props);
          
                this.state = {
                   data: 'Initial data...'
                }
          
                this.updateState = this.updateState.bind(this);
          
             };
          
             updateState() {
                this.setState({data: 'Data updated...'})
             }
          
             render() {
                return (
                   <div>
                      <button onClick = {this.updateState}>CLICK</button>
                      <h4>{this.state.data}</h4>
                   </div>
                );
             }
          }
          
          export default App;
          

          儿童活动

          import React from 'react';
          
          class App extends React.Component {
          
             constructor(props) {
                super(props);
          
                this.state = {
                   data: 'Initial data...'
                }
          
                this.updateState = this.updateState.bind(this);
             };
          
             updateState() {
                this.setState({data: 'Data updated from the child component...'})
             }
          
             render() {
                return (
                   <div>
                      <Content myDataProp = {this.state.data} 
                         updateStateProp = {this.updateState}></Content>
                   </div>
                );
             }
          }
          
          class Content extends React.Component {
          
             render() {
                return (
                   <div>
                      <button onClick = {this.props.updateStateProp.bind(this)}>CLICK</button>
                      <h3>{this.props.myDataProp}</h3>
                   </div>
                );
             }
          }
          
          export default App;
          

          Refer here

          【讨论】:

            【解决方案6】:

            您可以使用this.props.someProps() 触发事件。检查以下示例。

            import React, { Component } from 'react';    
            
            class AddToDo extends Component {
               render() {
                  return (
                     <button onClick={ev => this.props.handleAddToDo(ev, 'hello')}>
                        {this.props.title}
                     </button>
                  )
               }
            }
            
            class Todos extends Component {
               handleAddToDo(ev, someVal) {
                  // do something
               }
            
               render() {
                  return (
                     <AddToDo title="Add" handleAddToDo={(ev, someVal) => this.handleAddToDo(ev, someVal)} />
                  )
               }
            }
            
            export default Todos;
            

            【讨论】:

              猜你喜欢
              • 2016-06-15
              • 2018-04-01
              • 2021-01-09
              • 2023-01-22
              • 1970-01-01
              • 2022-12-03
              • 2020-11-24
              • 2017-01-30
              • 1970-01-01
              相关资源
              最近更新 更多