使用props和state在React数组中编辑文本值?

时间:2016-08-30 15:01:14

标签: javascript jquery reactjs

在尝试学习React时,我对如何处理这种情况很困惑。请记住,我仍然是脚本语言的新手。

我希望能够点击“编辑”并显示一个文本框,其中“名称”位于编辑按钮旁边,然后继续编辑文本。我无法弄清楚如何获得我点击的文本的价值。我知道如何使用for循环,但我正在尝试使用'反应方式'(使用道具和状态)。那是可行的吗?

handleEdit: function(e){
        e.preventDefault();
        var i = e.target.value; //index in the array
        var friendsCopy = this.state.friendsArray;
        console.log('SPACE.');
        console.log(/*the text of the value in the array*/);
}

我尝试过的所有内容都返回undefined或根本没有返回(空行)。 我尝试过使用data-属性,直接引用值(friendsCopy[e.text])和其他方式。我知道我没有得到任何东西而且我已经阅读了文档,但我似乎无法把它放在一起。

https://jsfiddle.net/nckdls/69z2wepo/54502/

1 个答案:

答案 0 :(得分:1)

修改后的JS小提琴:https://jsfiddle.net/wfn0eqtk/

通常你的代码是正确的,缺少的部分是提供正在编辑的朋友的索引。由于您已经有一个ShowList组件,我只是修改它以将click回调与正在编辑的项目的索引绑定,并将其触发到传入的prop。

triggerEdit: function(index, e) {
    this.props.handleEdit(index, e)
},

<button onClick={this.triggerEdit.bind(this, index)}>

最后,我修改了父组件中的handleEdit函数以接受新的索引参数,访问friendsCopy数组,并调用console.log结果。

handleEdit: function(editingIndex, e){
    var friendsCopy = this.state.friendsArray;
    var editingFriend = friendsCopy[editingIndex];
    console.log(editingFriend);
},

绑定参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Bind用于将范围(this的值)更改为函数,但也可用于传递其他参数。在这种情况下,在将其他参数传递给绑定函数之前注入参数。