javascript - 将项目添加到数组 React 时删除占位符

标签 javascript arrays reactjs

我有 5 个位置,其中有一个数字占位符可用于添加到数组中的项目出现,问题是我需要这些编号占位符在项目添加到数组后消失。

将项目添加到数组时如何删除编号占位符?

https://codesandbox.io/s/qlp47q8j26

Hello.js

import React from 'react';
import update from 'immutability-helper'
import styled from 'styled-components'
import Product from './Product'

const NumberWrap = styled.div`
  display: flex;
  flex-wrap:wrap
  border: 1px solid #ccc;
  flex-direction: row;
`

const Numbers = styled.div`
  display:flex;
  background: #fafafa;
  color: #808080;
  font-size: 32px;
  flex: 0 0 20%;
  min-height: 200px;
  justify-content: center;
  align-items:center;
  border-right: 1px solid #ccc;
`

const CardWrap = styled.div`
  display:flex;
  flex-wrap: wrap;
  flex-direction: row;
  margin-top: 20px;
`

export default class Hello extends React.Component {
  constructor() {
    super()
    this.state = {
      placeholder: [1,2,3,4,5],
      data: [
        { id: 1, header: 'Item 1'},
        { id: 2, header: 'Item 2'},
        { id: 3, header: 'Item 3'},
        { id: 4, header: 'Item 4'}
      ],
      addedItems: [],
    }
  }

  handleAdd = (id) => {
    this.setState({
        addedItems: update(this.state.addedItems, {
        $push: [
          id,
        ],
      })
    })
  }

  handleRemove = (id) => {
    const index = this.state.addedItems.indexOf(id);
    this.setState({
      addedItems: update(this.state.addedItems, {
        $splice: [
          [index, 1]
        ],
      })
    })
  }

  render() {
    return(
      <div>
        <NumberWrap>
          {
            this.state.placeholder.map(num =>
              <Numbers>{num}
              {
                this.state.data.filter(item => {
                  return this.state.addedItems.indexOf(item.id) === num - 1;
                }).slice(0, 5).map(item =>
                  <Product {...item} remove={() => { this.handleRemove(item.id) }} />
                )
              } 
              </Numbers>
            )
          }
        </NumberWrap>


        <CardWrap>
        {
          this.state.data.map(item =>
            <Product
              {...item}
              add={()=> {
                this.handleAdd(item.id) 
              }}
            />
          )}   
        </CardWrap>
      </div>
    )
  }
}

Product.js

import React from "react";
import styled from "styled-components";

const Card = styled.div`
  flex: 0 0 20%;
  border: 1px solid #ccc;
`;

const Header = styled.div`
  padding: 20px;
`;

const AddBtn = styled.button`
  width:100%;
  height: 45px;
`;

const Product = props => {
  const { add, id, header, remove } = props;
  return (
    <Card>
      <Header key={id}>
        {header}
      </Header>
      <AddBtn onClick={add}>Add</AddBtn>
      <AddBtn onClick={remove}>Remove</AddBtn>
    </Card>
  );
};

export default Product;

最佳答案

您应该将已添加数字的数组添加到您的状态,并且仅当该数组中不存在该数字时才渲染该数字。

  1. 我已将 addedArray 添加到构造函数中的状态。
  2. 修改了 handleAddhandleRemove 以删除和添加项目 新数组。

  3. 在 render 方法中添加了渲染 {num} 的条件。

这是Hello.js组件的修改后的代码:

import React from 'react';
import update from 'immutability-helper'
import styled from 'styled-components'
import Product from './Product'

const NumberWrap = styled.div`
  display: flex;
  flex-wrap:wrap
  border: 1px solid #ccc;
  flex-direction: row;
`

const Numbers = styled.div`
  display:flex;
  background: #fafafa;
  color: #808080;
  font-size: 32px;
  flex: 0 0 20%;
  min-height: 200px;
  justify-content: center;
  align-items:center;
  border-right: 1px solid #ccc;
`

const CardWrap = styled.div`
  display:flex;
  flex-wrap: wrap;
  flex-direction: row;
  margin-top: 20px;
`

export default class Hello extends React.Component {
  constructor() {
    super()
    this.state = {
      placeholder: [1,2,3,4,5],
      addedArray: [],
      data: [
        { id: 1, header: 'Item 1'},
        { id: 2, header: 'Item 2'},
        { id: 3, header: 'Item 3'},
        { id: 4, header: 'Item 4'}
      ],
      addedItems: [],
    }
  }

  handleAdd = (id) => {
    const nextAdded = [id,...this.state.addedArray];
    this.setState({
        addedArray: nextAdded,
        addedItems: update(this.state.addedItems, {
        $push: [
          id,
        ],
      })
    })
  }

  handleRemove = (id) => {
    const index = this.state.addedItems.indexOf(id);
    const nextAdded = this.state.addedArray.filter(n => n != id);
    this.setState({
      addedArray: nextAdded,
      addedItems: update(this.state.addedItems, {
        $splice: [
          [index, 1]
        ],
      })
    })
  }

  render() {
    return(
      <div>
        <NumberWrap>
          {
            this.state.placeholder.map(num =>
              <Numbers>
              {this.state.addedArray.filter(n=> n ==num).length == 0 && num}
              {
                this.state.data.filter(item => {
                  return this.state.addedItems.indexOf(item.id) === num - 1;
                }).slice(0, 5).map(item =>
                  <Product {...item} remove={() => { this.handleRemove(item.id) }} />
                )
              } 
              </Numbers>
            )
          }
        </NumberWrap>


        <CardWrap>
        {
          this.state.data.map(item =>
            <Product
              {...item}
              add={()=> {
                this.handleAdd(item.id) 
              }}
            />
          )}   
        </CardWrap>
      </div>
    )
  }
}

关于javascript - 将项目添加到数组 React 时删除占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46173179/

相关文章:

reactjs - 开 Jest - 覆盖率报告现在显示所有文件

reactjs - 如何在 react-router-dom v4.2.2 中获取当前路由

javascript - 如何删除工具提示中的数字

javascript - 下划线并需要为数组创建多个顺序

java - 读取txt文件并制作二维字符数组

javascript - 如何使用 Javascript 自动打印一系列 HTTP 搜索查询的搜索结果?

reactjs - 如何在 create-react-app 中以开发模式启用 Service Worker?

javascript - webpack 没有正确添加 [contenthash] 到我的 .js 文件

javascript - 更改自执行函数的上下文

JavaScript:替换数组中的字符串