You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React点击按钮创建Rnd组件问题求助:仅生成一个组件

Hey there! Let's figure out why you're only getting one Rnd component when clicking the button. The issue is likely that you're not tracking multiple widgets in your component's state—right now you probably have a single entry instead of an array to hold all the widgets you create.

To fix this, we'll use an array in your component's state to store each widget's unique data (like IDs, position, and size). Every time you click the button, we'll add a new widget object to this array, then map over the array to render all your Rnd components.

Here's the revised code with explanations:

import { Meteor } from 'meteor/meteor';
import React from 'react';
import ReactDOM from 'react-dom';
import { render } from 'react-dom';
import Rnd from 'react-rnd';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    // Initialize state with an empty array to hold all widgets
    this.state = {
      widgets: []
    };
    // Bind the click handler to keep correct context for 'this'
    this.addWidget = this.addWidget.bind(this);
  }

  addWidget() {
    // Create a new widget with a unique ID and default position/size
    const newWidget = {
      id: Date.now(), // Timestamp works as a quick unique ID
      x: 20 + (this.state.widgets.length * 30), // Offset new widgets to avoid overlap
      y: 20 + (this.state.widgets.length * 30),
      width: 200,
      height: 150
    };
    // Update state by adding the new widget to the existing array
    this.setState(prevState => ({
      widgets: [...prevState.widgets, newWidget]
    }));
  }

  render() {
    return (
      <div>
        {/* Button to trigger widget creation */}
        <button onClick={this.addWidget}>Add New Rnd Widget</button>
        {/* Render every widget in the state array */}
        {this.state.widgets.map(widget => (
          <Rnd
            key={widget.id} // Unique key is critical for React to track components
            style={{ backgroundColor: '#f0f0f0', border: '1px solid #ccc', padding: '10px' }}
            default={{
              x: widget.x,
              y: widget.y,
              width: widget.width,
              height: widget.height
            }}
          >
            <div>Widget #{widget.id.toString().slice(-4)}</div>
          </Rnd>
        ))}
      </div>
    );
  }
}

// Render the app to your root DOM element
render(<App />, document.getElementById('root'));

Key Changes Explained:

  • State Management: We use a widgets array in state to store all widget data instead of a single entry. This lets us track multiple components.
  • Add Widget Logic: The addWidget function creates a new widget object with unique properties, then updates state by spreading the existing array and adding the new widget (this avoids mutating the original state, which is a React best practice).
  • Rendering Multiple Widgets: We use map() on the widgets array to render an Rnd component for each entry. The key prop uses the widget's unique ID to help React efficiently update the DOM when the array changes.
  • Context Binding: We bind addWidget in the constructor to ensure this refers to the component instance when the button is clicked.

If you had an existing renderWidget method, you can refactor it to accept a widget object as a parameter and return the Rnd component, then call that method inside the map() function instead of writing the Rnd directly. The core idea remains the same: manage an array of widgets in state.

内容的提问来源于stack exchange,提问作者Atomator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:12:32