如何通过ReactJS中的文本框和按钮更改JSON数据?

时间:2017-10-07 16:02:59

标签: json reactjs

我刚开始学习反应。

请参阅下面的codepen链接中的代码。

按下编辑按钮时,表格中的字段将更改为文本框。

这就是我想要的。

我想再次点击编辑按钮。

如何替换JSON数据中的数据值?

非常感谢您的帮助。

let UsersData = [
  {Name: 'AAA',Last:"1111"},
  {Name: 'BBBB',Last:"222"},
]

  constructor(props) {
super(props)
this.state={
  Editing:false,
}
this.toggleEditing = this.toggleEditing.bind(this)}

toggleEditing() {
    let Editing = !this.state.Editing
    this.setState(
      {Editing: Editing}
    )}

CODEPEN的完整代码

Codepen https://codepen.io/StCrownClown/pen/MEQPzP?editors=0010

1 个答案:

答案 0 :(得分:2)

要首先更改您的JSON数据,您需要通过TextInput组件获取用户输入,为此,您需要定义valueonChange道具来存储值您所在州的输入。鉴于您的输入是自定义组件,我会将这些道具作为道具传递。

像这样:

class TextInput extends React.Component {
  render() {
    const {value, onChange, name} = this.props
    return (
      <td>
        <input type="text" 
          value={value} // to display the value
          onChange={onChange} // to store the value on the state
          name={name} // to use use the name as a property of the state
        />
      </td>
    )
  }
}

然后在您的TableRow组件状态中,您需要:

保存这些值并处理其更改:

this.state = {
    Editing:false,
    // from props to show their current value
    name : this.props.data.Name 
    last: this.props.data.Last
}

// to handle changes
onChange(event){
    this.setState({
      [event.target.name] : event.target.value
    })
  }

并将上述props传递给TextInput

<TextInput value={this.state.name} name="name" onChange={this.onChange}></TextInput>
<TextInput value={this.state.last} name="last" onChange={this.onChange} ></TextInput>

要在Editingfalse时向用户显示这些值,您需要:

为您的Table组件定义了一个状态,以便它根据更改重新呈现,并在用户完成编辑后更改该状态的函数:

 this.state = {
      UsersData: UsersData
 }

 saveChanges({key, name, last}){
    // key: unique identifier to change the correct value in the array
    // name: new Name
    // last: new Last
    this.setState(prevState => ({
      UsersData: prevState.UsersData.map(data => {
        if(data.Name === key) return { Name: name, Last: last }
        return data
      })
    }))
  }

最后,将该函数传递给TableRow组件:

const rows = [] 
 // now the loop is from the UsersData in the component state to see the changes  
this.state.UsersData.forEach((data) => {
  rows.push (
     <TableRow
        key={data.Name}
        saveChanges={this.saveChanges}
        data={data}
      />
   )
})

并在点击完成按钮时调用saveChanges组件中的TableRow函数:

saveChanges(){
   const {name , last} = this.state
    this.toggleEditing()
    this.props.saveChanges({
       key: this.props.data.Name,
       name,
       last
   }) 
 }


<button onClick={this.saveChanges} >Done</button>

您可以查看完整代码here