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

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

我正在维护存储在状态对象中的对象数组。基本上,每当我单击“添加”按钮时,我都会将每个对象推送到此数组。这会将此对象存储在数组中。

我还迭代了这个对象数组以显示在页面下方。

现在我正在尝试根据我单击的对象填充输入字段。我做不到。基本上,我点击的对象应该填充输入字段,然后我应该能够编辑它

不胜感激

对象数组的结构:

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

组件代码

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

根据代码的逻辑 showDetails 应该看起来像

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

只需将 user 设置为 users 数组的选定元素。 React 将进行更新并使用更新后的数据调用 render()

同时利用 splice 将从数组中删除当前正在编辑的用户。这遵循代码的逻辑。编辑后应单击 Add 将修改后的用户添加回数组。这可能不太方便,因此您可以考虑在 state 中添加 editingIndex 并指定当前正在编辑的用户对象。在这种情况下,您必须将所选对象的索引保存在 editingIndex 中。在 handleChange 中,您应该检查是否有一些用户对象现在正在编辑,并且不仅在 stateuser 属性 中而且在相应的 users 数组元素 [=25] 中修改数据=]

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