简体   繁体   English

在reactjs中的方法中的调用方法

[英]Call method within method in reactjs

I want to call a method inside another method like this, but it is never called. 我想在另一个这样的方法中调用一个方法,但从未调用过。

Button: 按键:

<span onClick={this.firstMethod()}>Click me</span>

Component: 零件:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {..};
  }

  firstMethod = () => (event) => {
    console.log("button clicked")
    this.secondMethod();
  }

  secondMethod = () => (event) => {
    console.log("this is never called!")
  }

  render() {..}
}

The first method is called, but not the second one. 第一个方法被调用,但第二个则不被调用。 I tried to add to the constructor 我试图添加到构造函数

this.secondMethod = this.secondMethod.bind(this);

which is recommended in all the other solutions but nothing seems to work for me. 在所有其他解决方案中都建议这样做,但似乎对我没有任何帮助。 How can I call the second method correctly? 如何正确调用第二种方法?

There are two problems here. 这里有两个问题。

First one: You are defining your functions wrong. 第一个:您定义的函数错误。

firstMethod = () => (event) => {
    console.log("button clicked")
    this.secondMethod();
}

Like this, you are returning another function from your function. 这样,您将从函数中返回另一个函数。 So, it should be: 因此,应为:

firstMethod = ( event ) => {
    console.log("button clicked")
    this.secondMethod();
}

Second: You are not using onClick handler, instead invoking the function immediately. 第二:您没有使用onClick处理程序,而是立即调用该函数。

<span onClick={this.firstMethod()}>Click me</span>

So, this should be: 因此,应为:

<span onClick={() => this.firstMethod()}>Click me</span>

If you use the first version, yours, when component renders first time your function runs immediately, but click does not work. 如果您使用的是第一个版本,则当组件首次呈现时,您的函数将立即运行,但单击不起作用。 onClick needs a handler. onClick需要一个处理程序。

Here, I totally agree @Danko's comment. 在这里,我完全同意@Danko的评论。 You should use this onClick with the function reference. 您应该将此onClick与功能参考结合使用。

<span onClick={this.firstMethod}>Click me</span>

With this method, your function is not recreated every time your component renders since it uses your handler function with its reference. 使用此方法,由于组件将处理程序函数与引用一起使用,因此不会在每次渲染组件时都重新创建您的函数。 Also, no struggle writing the handler manually. 同样,手动编写处理程序也毫不费力。

Lastly, if you define your functions as an arrow one, you don't need to .bind them. 最后,如果将功能定义为箭头,则无需将它们.bind

Here is the working code. 这是工作代码。

 class App extends React.Component { firstMethod = () => { console.log("button clicked") this.secondMethod(); } secondMethod = () => console.log("this is never called!") // or maybe even better not using an arrow function for the // second method since it is already bound to `this` since we // invoke it from the firstMethod. For details, look the comments please. /* secondMethod() { console.log("this is never called!") } */ render() { return( <span onClick={this.firstMethod}>Click me</span> ) } } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

代替firstMethod = () => (event)尝试firstMethod = (event) =>并且代替secondMethod = () => (event) => {尝试secondMethod = (event) => {

Your second method returns a new function, which is redundant. 第二种方法返回一个新函数,该函数是多余的。
Also, your second method can be not bound, since the first method has the context already. 同样,您的第二个方法不能绑定,因为第一个方法已经具有上下文。

secondMethod = () => (event) => { ... } should be secondMethod(evnt) { ... } secondMethod = () => (event) => { ... }应该是secondMethod(evnt) { ... }

Here is the working and optimized example https://codesandbox.io/s/pkl90rqmyj 这是工作和优化的示例https://codesandbox.io/s/pkl90rqmyj

The bad news is that you can't bind arrow functions because they're lexically bound. 坏消息是您不能bind箭头功能,因为它们是按词法绑定的。 See: 看到:

Can you bind arrow functions? 可以绑定箭头功能吗?

The good news is that "lexical binding" means that they should already have App as their this , ie it should would without explicitly binding. 好消息是,“词法绑定”意味着他们应该已经拥有App作为this ,即应该没有显式绑定。 You'd likely redefining them as undefined, or some other odd thing by treating them this way in the constructor. 您可能会通过在构造函数中以这种方式将它们重新定义为undefined或一些其他奇怪的事情。

Try this, it works for me. 试试这个,对我有用。

  firstMethod = () => {
    console.log("click handler for button is provided")
    return (event) => this.secondMethod(event);
  }

  secondMethod = (event) => {
    console.log("This is being called with", event);
  }

Can you check this way using this url: https://codesandbox.io/s/q4l643womw I think you're using wrong bind methods but here you can see an example 您可以使用以下网址检查这种方式吗: https : //codesandbox.io/s/q4l643womw我认为您使用的是错误的绑定方法,但是在这里您可以看到一个示例

class App extends Component {
  constructor() {
     super();
     this.state = {
       num: 1,
     };
     this.firstMethod = this.firstMethod.bind(this);
     this.secondMethod = this.secondMethod.bind(this);
  }

  firstMethod() {
    this.secondMethod();
  }

  secondMethod() {
    this.setState({
      num: 2
    });
  }

  render() {
    return (
      <div className="App">
        <button onClick={this.firstMethod}>click</button>
        <label>{this.state.num}</label>
      </div>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM