简体   繁体   English

如何在React中将事件处理程序作为prop传递?

[英]How to Pass an Event Handler as a prop in React?

I have two js files. 我有两个js文件。 1.Talker.js 2.Button.js 1.Talker.js 2.Button.js

Talker.js Talker.js

    import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from './Button';

class Talker extends React.Component {
  talk() {
    let speech = '';
    for (let i = 0; i < 10000; i++) {
      speech += 'blah ';
    }
    alert(speech);
  }

  render() {
    return <Button talk={this.talk} />;
  }
}

ReactDOM.render(
  <Talker />,
  document.getElementById('app')
);

Button.js Button.js

import React from 'react';

export class Button extends React.Component {
  render() {
    return (
      <button>
        Click me!
      </button>
    );
  }
}

I wanted to pass the 'talk' method to 'Button' .But when i change the code 我想将'talk'方法传递给'Button'。但是当我更改代码时

return <Button talk={this.talk} />;

in Talker class to 在Talker课程中

 return <Button talk={talk} />;

it also working fine.What is the use of 'this' key word here?Is it neccessary? 它也工作正常。这里使用'this'这个关键词是什么?是否有必要? What is the difference happen when i use the second piece of code? 当我使用第二段代码时会发生什么不同?

Cause Button does never call talk . 原因按钮并永远不会调用talk If you would accept it as a button property, eg: 如果你接受它作为按钮属性,例如:

 export class Button extends React.Component { 
   render() { 
      return <button onClick={this.props.talk} >Click me!</button>;
   }
 }

Then passing talk will fail, as talk is undefined and that cant be called. 然后传递talk将失败,因为talk未定义且无法调用。 So no, it is not working fine. 所以不,它没有正常工作。 Using this to refer to the context is mandatory. 使用this来引用上下文是强制性的。

You're not using the this.props.talk in the Button component, so it doesn't do anything when clicked, and you also don't get an error. 您没有在Button组件中使用this.props.talk ,因此单击时它不会执行任何操作,并且您也不会收到错误。

You need to do two things: 你需要做两件事:

1.) Add an onClick handler in your Button component. 1.)在Button组件中添加onClick处理程序。

<button onClick={this.props.talk}>click me</button>

2.) In your Talker component, make sure you're using this when you pass the prop. 2.)在你的Talker组件中,确保在通过道具时使用this If you try and do talk={talk} you'll get an error when you click the button, as talk is undefined . 如果您尝试并且执行talk={talk} ,则单击按钮时会出现错误,因为talk undefined What you're looking for is: talk={this.talk} to refer to the function talk() you defined in the Talker component. 您正在寻找的是: talk={this.talk}来指代您在Talker组件中定义的函数talk()

Working example here . 这里的工作示例。

Are you sure <Button talk={talk} />; 你确定<Button talk={talk} />; works? 作品? Because talk is undefined there so I'm a bit confused. 因为talk未定义,所以我有点困惑。 It shouldn't work. 它应该不起作用。

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

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