简体   繁体   English

如何在reactjs中单击时从数组中添加和删除元素?

[英]How can i add and remove elements from array on click in reactjs?

I'm trying to create a function that renders an array of links and i want to create a text input and a button that adds value from input in the array.我正在尝试创建一个呈现链接数组的函数,我想创建一个文本输入和一个按钮,用于从数组中的输入添加值。 I got the links saved in the state in the object that looks like this:我得到的链接保存在对象的状态中,如下所示:

sourceLinks: {
0: "https://www.w3schools.com/html/"
1: "https://www.apachefriends.org/docs/"
2: "https://docs.moodle.org/38/en/Windows_installation_using_XAMPP"
}

I've managed to render the links like this:我设法呈现这样的链接:

renderLinks() {
        
        let sessionLinks = this.state.sessionLinks;
        let links = [];
        Object.values(sessionLinks).map((link) => {
            links.push(<div className="column">
                <span>
                    <InputPreview inputValue={link} classes="w-300" />
                </span>
            </div>)
        })
        
        return links;

    }

InputPreview is the component i use for displaying links. InputPreview 是我用来显示链接的组件。 I'm tryin to add a text input and a button bellow the rendered links that adds the value to the array, and an icon next to every link that removes it from an array.我正在尝试在渲染链接下方添加一个文本输入和一个按钮,将值添加到数组中,并在每个链接旁边添加一个图标,将其从数组中删除。 I'm trying to do it all in one function renderLinks() and then call it in render.我试图在一个函数 renderLinks() 中完成所有操作,然后在渲染中调用它。 I know i have to push and slice items from an array and update the state but i'm strugling cause i just started learning react.我知道我必须从数组中推送和切片项目并更新状态,但我很挣扎,因为我刚刚开始学习反应。 Please help :)请帮忙 :)

You can add and render links with below code.您可以使用以下代码添加和呈现链接。

import React from "react";

class ItemList extends React.Component {
  state = {
    links: ["item1"],
    newItem: ""
  };

  submit(e, newLink) {
    e.preventDefault();
    let updatedLinks = this.state.links;
    updatedLinks.push(newLink);
    this.setState({ links: updatedLinks });
  }

  render() {
    return (
      <React.Fragment>
        <ul>
          {this.state.links?.map((link, i) => (
            <li key={i}>
              <p>{link}</p>
            </li>
          ))}
        </ul>
        <form onSubmit={(e) => this.submit(e, this.state.newItem)}>
          <input
            type="text"
            value={this.state.newItem}
            onChange={(e) => this.setState({ newItem: e.target.value })}
          />
          <button type="submit">ADD</button>
        </form>
      </React.Fragment>
    );
  }
}

export default ItemList;

Let me know for further clarificaton.让我知道进一步的澄清。

This is a example with functional components and hooks这是一个带有功能组件和钩子的例子

import React, { useState } from 'react';

const sourceLinks = [
  'https://www.w3schools.com/html/',
  'https://www.apachefriends.org/docs/',
  'https://docs.moodle.org/38/en/Windows_installation_using_XAMPP',
];

export const ListLinks = () => {
  const [links, setLinks] = useState(sourceLinks);
  const [newLink, setNewLink] = useState('');

  const handleAdd = () => {
    setLinks(links => [...links, newLink]);
  };
  const handleChangeNewLink = e => {
    const { value } = e.target;
    setNewLink(value);
  };
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <input type='text' value={newLink} onChange={handleChangeNewLink} />
        <button onClick={handleAdd}>Add</button>
      </div>
      <br />
      {links.map((link, index) => (
        <p key={index}>{link}</p>
      ))}
    </div>
  );
};

This is the result:这是结果:

在此处输入图片说明

Lastly, read the documentation, managing the state is essential.最后,阅读文档,管理状态是必不可少的。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM