繁体   English   中英

如何将 React 组件呈现的按钮绑定到该组件中的函数?

[英]How can I bind a button rendered by a React component to a function in that component?

我有一个名为 Quote 的组件,用于呈现随机生成的报价。 由于它们是随机生成的,它有一个更新它们状态的方法:

async update() {
        let response = await fetchQuote();
        console.log(response);
        this.setState({
            quoteAuthor: response.author,
            quote: response.quote
        });
    }   

并呈现为:

render() {
        return (
                <div className="main">
                    <h1>{this.state.quoteAuthor}</h1>
                    <p>{this.state.quote}</p>
                    <button onClick={this.update}>New quote</button>
                </div>
        );
    }

我想要按钮生成一个新的报价,但是当点击我得到Unhandled Rejection (TypeError): this is undefined 如果我将其修改为onClick={this.update()}它会以最快的速度快速更新而不会停止,无论我是否单击按钮。

这是整个班级:

/* component for the quote */
export default class Quote extends React.Component {
    /* placeholder */
    constructor(props) {
        super(props);
        this.state = {
            quoteAuthor: "Rick Osborne", 
            quote: "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
        }
    }
    /* actually render things */
    render() {
        return (
                <div className="main">
                    <h1>{this.state.quoteAuthor}</h1>
                    <p>{this.state.quote}</p>
                    <button onClick={this.update}>New quote</button>
                </div>
        );
    }

    /* async fetch the quotes and reassign the variables to them once processed */
    async update() {
        let response = await fetchQuote();
        console.log(response);
        this.setState({
            quoteAuthor: response.author,
            quote: response.quote
        });
    }   
}

您可以在组件的构造函数中绑定单击处理程序。 您还可以查看 React 的处理事件指南。

constructor(props) {
    super(props);

    this.state = {
        quoteAuthor: "Rick Osborne", 
        quote: "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
    }

    this.update = this.update.bind(this);
}

update函数更改为箭头函数,以便它指向上下文this

  update = async() => {
    let response = await fetchQuote();
    console.log(response);
    this.setState({
      quoteAuthor: response.quoteAuthor,
      quote: response.quote
    });
  };

这里的工作示例..

setState ,您可以从从 api 收到的响应中分配值。

你必须像这样编写函数。

Two ways to bind the function

  • 构造器模式
constructor(props) {
  super(props);

  this.state = {
    ...
  };

  this.update = this.update.bind(this);
}

  • 箭头功能模式
const update = async () => {
  ...
}

暂无
暂无

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

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