简体   繁体   English

想要根据点击 map() 中的一个对象来填充输入值:React+Typescript

[英]Want to populate the input values based on the click of an object inside map(): React+Typescript

I am maintaining an array of objects which is stored in a state object.我正在维护一个存储在状态对象中的对象数组。 Basically I am pushing each object to this array whenever I click on Add button .This stores this object in array.基本上,每当我单击“添加”按钮时,我都会将每个对象推送到这个数组。这会将这个对象存储在数组中。

Also I am iterating this array of objects to display down the page.此外,我正在迭代这个对象数组以向下显示页面。

Right now I am trying to fill the input fields based on the object that I have clicked.现在我正在尝试根据我单击的对象填充输入字段。 I am unable to do it.我做不到。 Basically, the object that I have clicked should populate the input fields and then I should be able to edit it基本上,我点击的对象应该填充输入字段,然后我应该能够编辑它

Help would be appreciated帮助将不胜感激

The structure of array of objects:对象数组的结构:

users= [
        {"name":"xxx","email":"yyy","phone":"656"},
        {"name":"yyy","email":"xxx","phone":"55"}
       ];

Component Code组件代码

import * as React from 'react';

interface IState{
    users : Account[];
    user: Account
}
interface Account{
  name: string;
  email: string;
  phone: string
}

export default class App extends React.Component<{},IState> {

    constructor(props:any){
       super(props);
       this.state= { 
                         users: [],
                         user: {
                                   name: '',
                                   email: '',
                                   phone: '',
                               }
                   }
    }

  removeAccount = (i:number) => {
    let users = [...this.state.users];
    users.splice(i,1);
    this.setState({users},()=>{console.log('setting the data')});
  }

  handleChange = ( event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({
      user:{
        ...this.state.user,
        [event.currentTarget.name]:event.currentTarget.value
      }
      })
  }

  onAdd = () => {
    e.preventDefault();
    this.setState({ 
                    users: [...this.state.users, this.state.user],
                    user: { name:'', email: '', phone: ''}
                  },()=>{console.log('adding')});
  }

  clearInputs = () => {
     this.setState({user: { name:'', email: '', phone: ''}});
  }

  showDetails = (i:number) => { //I need to populate the input fields based on the index of the object clicked.
     console.log(i);
  }

  render(){
    const { name, email, phone } = this.state.user;
   <React.Fragment>
     <form onSubmit={this.onAdd}>
       <input type="text" value={name} onChange={(e:any) => this.handleChange(e)} name={"name"} />
       <input type="text" value={email} onChange={(e:any) => this.handleChange(e)} name={"email"} />
       <input type="text" value={phone} onChange={(e:any) => this.handleChange(e)} name={"phone"} />
       <button type="submit">Add</button>
      </form>

      <ul>
          {this.state.users.map((row:any ,index: number) =>
            <li key={index}>
              <a onClick={()=> this.showDetails(index)}><span>{row.name}</span></a> // on click of this,i need to display the values corresponding to this object in the above input fields
              <i className="close far fa-times" onClick={() =>this.removeAccount(index)}/>
            </li>
          )}
      </ul>

   </React.Fragment>
  }
}

Based on logic of the code showDetails should look like基于代码的逻辑showDetails应该看起来像

showDetails = (i:number) => { 
    this.setState ({user: this.state.users.splice(i,1)});
    console.log(i);
}

Just set user to the selected element of users array.只需将user设置为users数组的选定元素。 React will do update and calls render() with updated data. React 将执行更新并使用更新的数据调用render()

Also utilizing splice will remove currently editing user from array.还使用splice将从数组中删除当前正在编辑的用户。 THis follow logic of the code.这遵循代码的逻辑。 After edit Add should be clicked to add modified user back to array.编辑后Add ,应点击添加修改用户返回到阵列。 This may be not convenient, so you may consider adding editingIndex to state and specify which user object currently editing.这可能不方便,因此您可以考虑在state添加editingIndex并指定当前正在编辑的用户对象。 In such case you'll have to save index of selected object in editingIndex .在这种情况下,您必须在editingIndex保存所选对象的editingIndex In handleChange you should check if some user object editing now and modify data not only in user property of state but in corresponding users array elementhandleChange您应该检查是否现在正在编辑某些用户对象并不仅在state user属性中而且在相应的users数组元素中修改数据

interface IState{
    users : Account[];
    user: Account;
    editingIndex: number | null;
}

// In constructor
constructor(props:any){
   super(props);
   this.state= { 
                     users: [],
                     user: {
                               name: '',
                               email: '',
                               phone: '',
                           },
                     editingIndex: null
               }
}
showDetails = (i:number) => { 
    this.setState ({user: this.state.users[i], editingIndex: i});
    console.log(i);
}

handleChange = ( event: React.ChangeEvent<HTMLInputElement>) => {
    let user = {...this.state.user,
        [event.currentTarget.name]:event.currentTarget.value};
    this.setState({user});
    // If we currently editing existing item, update it in array
    if (this.state.editingIndex !== null) {
        let users = [...this.state.users];
        users[this.state.editingIndex] = user;
        this.setState({users});
    }
}
removeAccount = (i:number) => {
   let users = [...this.state.users];
   // If we're going to delete existing item which we've been editing, set editingIndex to null, to specify that editing ends
   if (this.state.editingIndex === i)
       this.setState({user: {name: '', email: '', phone: ''}, editingIndex: null});
   users.splice(i,1);
   this.setState({users},()=>{console.log('setting the data')});
 }

 onAdd = () => {
    e.preventDefault();
    // If we NOT editing, but adding new editingIndex will be null so add user to users array. If we editing existing element it's no need to add it once again.
    if (this.state.editingIndex === null)
        this.setState({ users: [...this.state.users, this.state.user] });
    this.setState ({ editingIndex: null, 
                user: { name:'', email: '', phone: ''}
              },()=>{console.log('adding')});
 }
 // render will have no change

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

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