简体   繁体   English

React 如何在同一个父组件上显示多个不同来源的组件

[英]React how to display multiple components of different origin on the same parent component

I'm trying to build a Dashboard with React Js and I would like to know how you could display multiple components, but as widgets, which mean you need to be able to add them in any order and in any quantity.我正在尝试使用 React Js 构建仪表板,我想知道如何显示多个组件,但作为小部件,这意味着您需要能够以任何顺序和任何数量添加它们。 My problem is that I can't find a way to render a map of components.我的问题是我找不到渲染组件的 map 的方法。

The user may be able to add a widget to his dashboard by clicking a button, or remove them the same way, so I won't know how many of what components will be rendered用户可以通过单击按钮将小部件添加到仪表板,或者以相同的方式删除它们,所以我不知道将呈现多少个组件

I would like to do something like, when the user clicks on a widget, it adds it to the dashboard, but I don't know how to do that.我想做一些类似的事情,当用户点击一个小部件时,它将它添加到仪表板,但我不知道该怎么做。

I've tried to store components in a map, then with a forEach loop display them all by returning a div containing the component:我尝试将组件存储在 map 中,然后使用 forEach 循环通过返回包含该组件的 div 来显示它们:

import Weather from '...'
import Currency from '...'
import News from '...'

const map = [Weather, Currency, News]

const runAll = () => {
    map.forEach((fcn) => {
        let runner = fcn
        runner()
    })
}

runAll()

I've searched many stack and other forums questions, without finding what I needed我搜索了许多堆栈和其他论坛问题,但没有找到我需要的

Do you guys have an idea of what I could do to solve this?你们知道我能做些什么来解决这个问题吗?

Keep a state (array) that holds widgets added by user.保留一个包含用户添加的小部件的 state(数组)。 Define constants for widgets and save these constants to your persistance storage.为小部件定义常量并将这些常量保存到您的持久性存储中。

const widgets = {weather: 1, news: 2} save these values to database as json with properties configured by user if needed, and then retrieve this json and render components based on it const widgets = {weather: 1, news: 2} 将这些值作为 json 保存到数据库,如果需要,用户可以配置属性,然后检索这个 json 并基于它渲染组件

sample JSON structure to save - [{type: 1, prop1: "val"},{type: 2, prop1: "val"}]示例 JSON 结构保存 - [{type: 1, prop1: "val"},{type: 2, prop1: "val"}]

const renderWidgets = (array) => {
    const widgets = [];
    array.foreach((widget) => {
        switch(widget) {
            case widgets.weather:
                widgets.push(<Weather ...props/>);
            break;
            .
            .
            .
            etc
        }
    });
    
    return widgets;
}

So you need to be able to easily render 2 things:所以你需要能够轻松地渲染两件事:

  1. a list of widgets that the user can click and add in the dashboard用户可以单击并在仪表板中添加的小部件列表
  2. the actual dashboard.实际的仪表板。 All selected widgets in a list (with a remove capability)列表中所有选定的小部件(具有删除功能)

Let's first figure out what our state should be that also feeds the components 1 and 2.让我们首先弄清楚我们的state应该是什么,它也为组件 1 和 2 供电。

  • For the 1st one we need the full list of available widgets.对于第一个,我们需要可用小部件的完整列表。 Since this is static (we have 3 widgets available) this can be expresses through a static mapping (a simple javascript object) declared once.由于这是 static(我们有 3 个可用的小部件),这可以通过声明一次的 static 映射(一个简单的 javascript 对象)来表达。
  • For the 2nd one we need an array of the user selected widgets.对于第二个,我们需要一组用户选择的小部件。 That's the dynamic part.这就是动态部分。 We need to be able to set the initial widgets shown and have the capability to add and remove widgets from this list, allowing the same widget appearing more that once.我们需要能够设置显示的初始小部件,并能够从该列表中添加删除小部件,从而允许相同的小部件多次出现。

Static widget mapping Static 小部件映射

This should be a mapping between an identifier and the react widget component and should look like this:这应该是标识符和反应小部件组件之间的映射,应该如下所示:

import News from "./News";
import Weather from "./Weather";
import Currency from "./Currency";

const widgetsMapping = {
  news: News,
  weather: Weather,
  currency: Currency
};

Widgets state小部件 state

This is an array of widget identifiers (the keys from the static mapping) that the user wants in the dashboard.这是用户在仪表板中想要的一组小部件标识符(来自 static 映射的键)。 Also we need add and remove methods.我们还需要添加删除方法。 Using useState we can write this like below:使用useState我们可以这样写:

const [widgets, setWidgets] = useState(["weather", "news"]);

const addWidget = (widget) => {
  setWidgets([...widgets, widget]);
};

const removeWidget = (index) => {
  const updated = [...widgets];
  updated.splice(index, 1);
  setWidgets(updated);
};

Rendering渲染

Dashboard仪表板

Then we can render the dashboard by iterating our widget state array:然后我们可以通过迭代我们的widget state 数组来呈现仪表板:

{widgets.map((widget, index) => {
  const Widget = widgetsMapping[widget];
  return (
    <Widget
      key={`${widget}${index}`}
      removeWidget={() => removeWidget(index)}
    />
  )
})}

removeWidget prop can be used to let a widget remove itself when sth is clicked. removeWidget属性可用于让小部件在单击某物时自行移除。

List of available widgets可用小部件列表

Here we will iterate through all available widgets from our static mapping and render all of them with the add functionality bound to them.在这里,我们将遍历 static 映射中的所有可用小部件,并使用绑定到它们的添加功能来渲染所有这些小部件。

{Object.keys(widgetsMapping).map((widget) => (
  <button key={widget} onClick={() => addWidget(widget)}>
    {widget}+
  </button>
))}

You can find a full working example in this code sandbox .您可以在此代码沙箱中找到完整的工作示例 Some assumptions were made about how you want to add and remove widgets but the main idea remains the same.对如何添加和删除小部件进行了一些假设,但主要思想保持不变。

暂无
暂无

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

相关问题 如何从同一个父组件打开多个组件的模式 - How to open modal for multiple components from same parent component 当两个子组件相同且父组件在条件上不同时如何反应渲染 - How react render when both child components are same and parent component differs on condition 父组件中的多个子组件具有相同的实例angular2 - Multiple child components in parent component have the same instance angular2 在 React 中从多个子组件向一个父组件发送信息 - Send information from multiple children components to one parent component in React 如何在 react-native 的父组件内的特定 position 中显示多个组件? - How to show multiple components in a specific position inside of a parent component in react-native? 单击按钮显示不同的组件(反应组件类) - Display a different components in a click of a button (react component class) 如何渲染具有不同组件名称的多个组件? - How to render multiple components with different component name? 如何测试具有多个子组件的 React 组件? - How to test a React component with multiple child components? 如何将多个事件侦听器从React中的父组件附加到子组件的同一事件中? - How do I attach multiple event listeners to the same event of a child component from its parent component in React? React:如何动态地将不同类型的子组件附加到父组件中? - React: How to dynamically append child components of differing types into a parent component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM