javascript - React button component onClick() fires on page load, not onclick - Stack Overflow

My onClick isn't firing on click, but rather when the page loads. Here's the relevant code:Ap

My onClick isn't firing on click, but rather when the page loads. Here's the relevant code:

App.js

callAPI(x) {
    fetch("http://localhost:8080/" + x)
      .then(res => res.text())
      .then(res => this.setState({ apiResponse: res }))
      .catch(err => err);
  }

render() {
    <Button
       onClick={this.callAPI('api')}
       type="success"
       className="input-lg">
       Search
    </Button>

Button ponent:

import React from "react";

function Button({ type = "default", className, children, onClick }) {
  return (
    <button onClick={onClick} className={["btn btn-lg", `btn-${type}`, 
    className].join(" ")}>
      {children}
    </button>
  );
}

export default Button;

Any help is greatly appreciated!

My onClick isn't firing on click, but rather when the page loads. Here's the relevant code:

App.js

callAPI(x) {
    fetch("http://localhost:8080/" + x)
      .then(res => res.text())
      .then(res => this.setState({ apiResponse: res }))
      .catch(err => err);
  }

render() {
    <Button
       onClick={this.callAPI('api')}
       type="success"
       className="input-lg">
       Search
    </Button>

Button ponent:

import React from "react";

function Button({ type = "default", className, children, onClick }) {
  return (
    <button onClick={onClick} className={["btn btn-lg", `btn-${type}`, 
    className].join(" ")}>
      {children}
    </button>
  );
}

export default Button;

Any help is greatly appreciated!

Share Improve this question asked Apr 1, 2019 at 17:24 wangdoodlewangdoodle 312 silver badges7 bronze badges 1
  • Hi Andy, could you accept one of the answers to close the question? – Dupocas Commented Apr 1, 2019 at 19:23
Add a ment  | 

3 Answers 3

Reset to default 3

Change

<Button onClick={this.callAPI('api')} type="success" className="input-lg">
  Search
</Button>

to

<Button onClick={() => this.callAPI('api')} type="success" className="input-lg">
  Search
</Button>

You are calling the function as soon as the prop is set instead of when it is clicked. To get the function to fire when clicked you need to pass in a function that has not been called.

It's becouse you use fire it up automatically. Try something like this.

 <Button
   onClick={() => this.callAPI('api')}
   type="success"
   className="input-lg">
   Search
</Button>
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Change

onClick={this.callAPI('api')}

To

onClick={() => this.callAPI('api')}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745133156a4613071.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信