首页 > 解决方案 > 使用 onClick 无休止地重新渲染 React 组件

问题描述

我希望 result.js 中按钮的 onClick 事件呈现我的 Spinner 组件,并且到目前为止(有点)让它这样做。目前,Spinner 主要有一些 console.log() 语句,并且它一直在记录“Rendered spinner”。单击按钮后无休止,大约每秒一次。作为记录,返回的段落没有显示,但我还没有开始调试它。另外,我在 Result.js 中排除了一些我认为不相关的代码。

现在,我只想让 Spinner 在按下按钮后只渲染一次。有小费吗?

结果.js:

import React, { Component } from "react";
import { connect } from "react-redux";
import Spinner from "./spinner";

class UnboxResult extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showSpinner: false
    };
    this.handleUnboxClicked = this.handleUnboxClicked.bind(this);
  }

  handleUnboxClicked(event) {
    event.preventDefault();
    console.log("Inside handleUnboxClicked");
    this.setState({
      showSpinner: true
    });
  }

  render() {

    return (
      <section className="opening">
        <div className="container">
          <div className="row">
            <button onClick={this.handleUnboxClicked}>UNBOX</button>
          </div>
          <div className="row">
            {this.state.showSpinner ?
              <Spinner items={this.props.unbox.items}/> :
              null}
          </div>
        </div>
      </section>
    );
  }
}

export default connect(state => ({
  unbox: state.unbox
}))(UnboxResult);

微调器.js:

import React, { Component } from 'react';

class Spinner extends Component {
  constructor(props) {
    console.log("Before super");
    super(props);
    console.log("Ran constructor.");
  }

  render(){
    console.log("Rendered spinner.");
    return(
    <p>Spinning..</p>
    );
  }
}
export default Spinner;

标签: javascriptreactjs

解决方案


您可以添加一个处理程序方法来更新微调器的状态

handleClick(){
  this.setState({
    showSpinner: true
  })
}

在你的渲染中它需要作为道具传递

<div className="row">
  {this.state.showSpinner ?
    <Spinner handleClick={this.handleClick}/> :
    null}
</div>

在您的微调器组件返回中,您可以使用 onclick 触发它

<button onClick = {this.props.handleClick} > Click </button>

这将允许您更新父项中的状态,您可能想弄清楚如何在微调器中一次显示一个项目,并且仅在没有项目可显示时将状态设置为 false。

对不起,如果我误解了你的评论。


推荐阅读