2017-08-16 28 views
0

我有对象的一个​​这样的数组:如何将文本输入中的对象添加到原生反应中的数组中?

const data = { 
    0: { 
    isEditing:false, 
    text: 'Chloe', 
    }, 
    1: { 
    isEditing:false, 
    text: 'Jasper', 
    }, 
    2: { 
    isEditing:false, 
    text: 'Pepper', 
    }}; 

我想创建这样的一个add方法,但我不知道怎么下指数在要插入项目。我无法更改数组的结构,因为我需要使用可排序列表库进行拖放操作。

这里是我的代码:

export default class App extends Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     inputValue: "", 
     db: [] 
    }; 
    this.textChange = this.textChange.bind(this); 
    this.addTask = this.addTask.bind(this); 
    } 

    textChange = value => { 
    const inputValue = value; 
    this.setState(() => ({ 
     inputValue 
    })); 
    }; 
    addTask =() => { 
    if (!this.state.inputValue) { 
     return; 
    } 
    //this.state.db.push({ 
    // isEditing:false, 
    // text: this.state.inputValue 
    // }); 

    data.index = { 
      isEditing:false, 
      text: this.state.inputValue  
    } 

    index++; 

    this.setState({ 
     ...this.state, 
     data:this.state.data, 
     inputValue: "" 
    }); 
    // rowsState - array: {text, isEditing} 
    }; 


} 

回答

0

我设法找到答案。

addTask =() => { 
    if (!this.state.inputValue) { 
     return; 
    } 

    let newData = {}; 

    let l = Object.keys(this.state.data).length; 
    console.log("l=", l); 
    let i = 0; 
    for (i = 0; i < l; i++) { 
     let el = this.state.data[i]; // i + "" 
     newData[i] = el; 
    } 

    newData[l] = { text: this.state.inputValue, isEditing: false }; 

    this.setState({ 
     ...this.state, 
     data: newData, 
     inputValue: "" 
    }); 
    }; 
相关问题