简体   繁体   English

正确将功能绑定到Button onClick

[英]Correctly bind a function to Button onClick

This is a React-Bootstrap-Button: 这是一个React-Bootstrap-Button:

<Button onClick={console.log('Hello')} className="pull-right">Try me</Button>

I want the function to execute everytime a click the button. 我希望函数每次单击按钮后都执行。 However, it will execute on pageload. 但是,它将在页面加载时执行。 I read somewhere that I should bind the function: 我读到某个地方应该绑定该函数:

<Button onClick={console.log('Hello').bind(null)} className="pull-right">Try me</Button>

This gives me the error: Uncaught (in promise) TypeError: Cannot read property 'bind' of undefined. 这给了我错误:未捕获(承诺)TypeError:无法读取未定义的属性“ bind”。

What should I do? 我该怎么办?

You are calling log immediately and then trying to bind its return value (which is undefined ). 您正在立即调用log ,然后尝试bind其返回值( undefined )。

You need to bind the function itself. 您需要绑定函数本身。

You also need to bind it to the console context and not the null context. 您还需要将其绑定到console上下文,而不是null上下文。 log cares about the object it is attached to. log关心它所附加的对象。

onClick={console.log.bind(console, 'Hello')}

Idiomatic React would create the function separately instead of trying to do it inline though: 惯用的React将单独创建函数,而不是尝试内联地执行该函数:

function myFunction () {

  function handleClick(e) {
    e.preventDefault();
    console.log('Hello');
  }

  return (
    <Button onClick={handleClick} className="pull-right">Try me</Button>

  );
}

I think this is what you want: 我认为这是您想要的:

<button onclick="javascript:console.log('Hello');" className="pull-right">Try me</button>

Notice onclick="javascript:console.log('Hello');" 请注意onclick="javascript:console.log('Hello');" .

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

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