【问题标题】:Want to populate the input values based on the click of an object inside map(): React+Typescript想要基于点击 map() 中的对象来填充输入值:React+Typescript
【发布时间】:2019-09-24 19:30:03
【问题描述】:

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

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

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

我们将不胜感激

对象数组的结构:

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

【问题讨论】:

    标签: reactjs typescript react-component


    【解决方案1】:

    基于代码showDetails 的逻辑应该是这样的

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

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

    同样使用splice 将从数组中删除当前正在编辑的用户。这遵循代码的逻辑。编辑后Add 应单击以将修改后的用户添加回数组。这可能不方便,因此您可以考虑将editingIndex 添加到state 并指定当前正在编辑的用户对象。在这种情况下,您必须将所选对象的索引保存在editingIndex 中。在handleChange 中,您应该检查是否某些用户对象现在正在编辑,并且不仅在stateuser 属性中而且在相应的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
    

    【讨论】:

    • 完美!非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多