簡體   English   中英

想要根據點擊 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保存所選對象的editingIndex handleChange您應該檢查是否現在正在編輯某些用戶對象並不僅在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