Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在单击reactjs时从数组中添加和删除元素?_Javascript_Arrays_Reactjs - Fatal编程技术网

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

Javascript 如何在单击reactjs时从数组中添加和删除元素?,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我试图创建一个函数来呈现一个链接数组,我想创建一个文本输入和一个按钮,从数组中的输入中添加值。我获得了保存在对象状态中的链接,如下所示: sourceLinks: { 0: "https://www.w3schools.com/html/" 1: "https://www.apachefriends.org/docs/" 2: "https://docs.moodle.org/38/en/Windows_installation_using_XA

我试图创建一个函数来呈现一个链接数组,我想创建一个文本输入和一个按钮,从数组中的输入中添加值。我获得了保存在对象状态中的链接,如下所示:

sourceLinks: {
0: "https://www.w3schools.com/html/"
1: "https://www.apachefriends.org/docs/"
2: "https://docs.moodle.org/38/en/Windows_installation_using_XAMPP"
}
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;

    }
我已经成功地呈现了如下链接:

sourceLinks: {
0: "https://www.w3schools.com/html/"
1: "https://www.apachefriends.org/docs/"
2: "https://docs.moodle.org/38/en/Windows_installation_using_XAMPP"
}
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;

    }
renderLinks(){
让sessionLinks=this.state.sessionLinks;
让链接=[];
Object.values(sessionLinks).map((link)=>{
links.push(
)
})
返回链接;
}

InputPreview是我用来显示链接的组件。我正在尝试添加一个文本输入和一个按钮,该按钮位于向数组添加值的渲染链接下方,并在从数组中删除该值的每个链接旁边添加一个图标。我正试图在一个函数renderLinks()中完成这一切,然后在render中调用它。我知道我必须从数组中推送和切分项目并更新状态,但我正在挣扎,因为我刚刚开始学习如何反应。请帮助:)

您可以使用以下代码添加和呈现链接

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;
从“React”导入React;
类ItemList扩展了React.Component{
状态={
链接:[“项目1”],
新项目:“
};
提交(e,新链接){
e、 预防默认值();
让updatedLinks=this.state.links;
updatedLinks.push(newLink);
this.setState({links:updatedLinks});
}
render(){
返回(
    {this.state.links?.map((link,i)=>(
  • {link}

  • ))}
this.submit(e,this.state.newItem)}> this.setState({newItem:e.target.value}) /> 添加 ); } } 导出默认项目列表;

让我知道进一步的澄清。

这是一个带有功能组件和挂钩的示例

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>
  );
};

import React,{useState}来自“React”;
常量源链接=[
'https://www.w3schools.com/html/',
'https://www.apachefriends.org/docs/',
'https://docs.moodle.org/38/en/Windows_installation_using_XAMPP',
];
导出常量列表链接=()=>{
const[links,setLinks]=useState(sourceLinks);
const[newLink,setNewLink]=useState(“”);
常数handleAdd=()=>{
setLinks(links=>[…links,newLink]);
};
常量handleChangeNewLink=e=>{
const{value}=e.target;
setNewLink(值);
};
返回(
添加

{links.map((链接,索引)=>(

{link}

))} ); };
结果是:


最后,阅读文档,管理状态是必不可少的。

这是可行的,但并不完全可行。它确实会更改state.link并在数组中添加新链接,但不会显示(呈现)新数组。它只显示带有现有链接的旧数组。我已经创建了沙盒供您参考。请检查它,谢谢,这很有用,但是我可以使用基于类的组件吗?