最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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')}
发布评论

评论列表(0)

  1. 暂无评论