Javascript 在 React 中调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45099748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:54:42  来源:igfitidea点击:

Calling a function in React

javascriptreactjsjsxdom-events

提问by Anyname Donotcare

I'm a beginner in React, and I'm a little confused about calling a function in React.

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

I saw the following ways and I don't know when to use each and which one.

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

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

Are these interchangeable? Could I do that to handle an event, the same way to call a function?

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

回答by Chris

Are these interchangeable?

这些可以互换吗?

Short answer: No.

简短的回答:没有。



Let's take a look at the different snippets you've posted:

让我们来看看您发布的不同片段:



someFunction()vs someFunction

someFunction()对比 someFunction

With the former syntax, you are actually invoking that function. The latter is just a reference to that function. So when do we use which?

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

  • You would use someFunction()when you want that function invoked and its result returned immediately. In React, this is typically seen when you split parts of your JSX code to a separate function; either for reasons of readability or reusability. For example:

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

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


  • You would use someFunctionwhen you want only to pass the reference to that function to something else. In React, this is usually an event handler that is passed down to another child-component via propsso that that component can call the event handler when it needs to. For example:

    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当您只想将该函数的引用传递给其他函数时,您会使用它。在 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()vs this.someFunction()

someFunction()对比 this.someFunction()

This has to do with the context of the function. Basically, "where is this function?". Is part of the current Component, then use this.someFunction(), is it part of the parent Component passed in as props, then use this.props.someFunction(). Is it a function inside the current method, then just use someFunction().

这与函数的上下文有关。基本上,“这个功能在哪里?”。是当前 Component 的一部分,然后使用this.someFunction(),它是作为 props 传入的父 Component 的一部分,然后使用this.props.someFunction(). 它是当前方法中的一个函数,然后只需使用someFunction().

Obviously, there's a lot more to it than that, but it's the best basic summary I can give.

显然,它的内容远不止这些,但这是我能给出的最好的基本总结。

For a better understanding, have a read here. It is a great guide to how the thiskeyword works in Javascript and in React in particular.

为了更好地理解,请阅读此处。这是一个很好的指南,说明this关键字在 Javascript 中的工作方式,特别是在 React 中。

回答by Yury Tarabanko

If you want to calla function options 2 and with some assumptions 5 should work.

如果你想调用一个函数选项 2 并且有一些假设 5 应该可以工作。

If you want to actually passa function as a property to some child component so that it could call it later (say to notify your root element on some event) then option 1 (with prebind) and 3 (with defining a variable const {handleAddTodo} = thisand prebind :) ) should work

如果您想一个函数作为属性实际传递给某个子组件,以便它可以稍后调用它(比如在某个事件上通知您的根元素),那么选项 1(使用 prebind)和 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()} 

回答by fauster01

To call the functionyou have to add ()

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

{this.handleAddTodo()}   

About handling events - Handling#Events

关于处理事件 -处理#Events

Arrow Functions - Functions#ArrowFunctions

箭头函数 - Functions#ArrowFunctions

回答by Voi M?p

In ES6 you can use normal function or Arrow Function:

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

Function1 (Normal Function)

功能 1(正常功能)

functionA(){
   //Something here
}

Then should call this.functionA()

然后应该调用this.functionA()

Function2 (ArrowFunction)

函数 2(箭头函数)

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

Then should call this.functionA

然后应该调用this.functionA

*Function3 (Eg: in a const of React) *

*Function3(例如:在 React 的常量中)*

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

functionTestis mapStateToProps in React :)

functionTest是 React 中的 mapStateToProps :)

I hope it is helpful for you :)

我希望它对你有帮助:)

回答by vnomvk

this is correct -> handleAddTodo ={this.handleAddTodo}When function passing to child component you have to bind your function like this handleAddTodo ={this.handleAddTodo.bind(this)}. below code help out your doubt.

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

Simple Example

简单示例

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;

Child Events

儿童活动

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

参考这里

回答by Abraham Gnanasingh

You can trigger events with this.props.someProps(). Check the following sample.

您可以使用 触发事件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;