【问题标题】:I want to add this Card Component dynamically when the button is pressed. So if i press the button 3 times, 3 cards must be added to the DOM我想在按下按钮时动态添加这个卡片组件。因此,如果我按 3 次按钮,则必须将 3 张卡片添加到 DOM
【发布时间】:2020-08-18 02:44:24
【问题描述】:

我想在按下按钮时动态添加这个卡片组件。因此,如果我按下按钮 3 次,则必须将 3 张卡片添加到 DOM。有人可以帮我弄清楚为什么这不起作用,我是新手。提前致谢。是不是因为我不能在渲染方法之外使用组件

import React, {Component} from 'react';
import Card from './Card'

class App extends Component {

  addRobotHandler = () => {
    return (
      <Card/>
    )
  }
  render() {
    return (
      <div>
        <button onClick={this.addRobotHandler}>Click me to see Robots</button>
      </div>
    );
  }
}

export default App;

【问题讨论】:

    标签: reactjs react-component


    【解决方案1】:

    您可以添加一个定义计数数量的状态,并在您的渲染函数中渲染该数量的卡片。

    // sample example
    class Example extends Component {
      constructor(props) {
        super(props);
        this.state = {
          cardsCount: 0
        };
      }
    
      addRobotHandler = () => {
        this.setState(prevState => {
          return { cardsCount: prevState.cardsCount + 1 };
        });
      };
    
      getCards = ()  => {
        let cards = [];
        for(let i = 0; i < this.state.cardsCount; i++) {
          cards.push(<Cards/>)
        }
        return cards;
      }
    
      render() {
        return (
          <div>
            <button onClick={this.addRobotHandler}>Click me to see Robots</button>
            {this.getCards()}
          </div>
        );
      }
    }
    

    【讨论】:

    • 我想知道是学习和使用 redux 还是反应钩子和上下文 API。我已经对使用 redux 有了初步的了解。 React Hooks 是未来吗,我现在是不是应该把所有的精力都集中在 Hooks 上,是否需要对 Redux 有很好的了解才能学习 Hooks 和 context API?
    • 你现在不需要redux。通过 hooks 和 context api.. 然后 redux..
    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 2020-12-18
    • 2019-10-04
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多