简体   繁体   English

如何从选择标签传递数组对象并将值传递给 API?

[英]How to pass array object from select tag and pass values into API?

I have two components.我有两个组件。 From componentA i am getting value of roles fields and using this values i need to create another record for componentB of users .从 componentA 我得到了roles字段的值,并使用这个值我需要为users componentB 创建另一个记录。

The structure of componentA is like this: componentA的结构是这样的:

[
  {
    "id": "507f1f77bcf86cd799439011",
    "title": "admin",
    "status": "active"
  },
  ...
]

The structure of componentB is like this in which i am getting roles data and when i create another record then at that time the value of roles should be inserted like this format. componentB 的结构是这样的,我在其中获取角色数据,当我创建另一个记录时,应该像这种格式那样插入角色的值。

[
  {
    "id": "507f1f77bcf86cd799439017",
    "email": "admin@admin.com",
    "roles": {
      "id": "507f1f77bcf86cd799439011",
      "title": "admin",
      "status": "active"
    }
  },
  ...
]

=> User insert component to insert records. => 用户插入组件以插入记录。

import { BootstrapTable, TableHeaderColumn } from "react-bootstrap-table";
import RolesField from "./Editor/Roles/Field";

class UserInsertRow extends React.Component {
  constructor(props) {
    super(props);
    this.roles = [];
    this.getRoles();
  }

  customRoleField = (
    column,
    attr,
    editorClass,
    ignoreEditable,
    defaultValue
  ) => (
    <RolesField
      roles={this.roles}
      ref={attr.ref}
      {...this.props}
      editorClass={editorClass}
      ignoreEditable={ignoreEditable}
    />
  );

  render() {
    return (
      <BootstrapTable
        ref="table"
        insertRow={true}
        deleteRow={true}
        pagination={true}
        data={this.props.data}
      >
        <TableHeaderColumn
          dataField="role"
          customInsertEditor={{ getElement: this.customRoleField }}
          customEditor={{
            getElement: this.roleEditor,
            customEditorParameters: { roles: this.roles }
          }}
        >
          Role
        </TableHeaderColumn>
      </BootstrapTable>
    );
  }
}

=> RolesField component => RolesField 组件

import { rolesContext } from "../../Context";
class RolesField extends React.Component {
  constructor(props) {
    super(props);
  }

  getFieldValue = () => rolesContext._currentValue.selectedRoles;

  render() {
    console.log(this.props.roles);
    return (
      <div className="form-group">
        <select
          className="form-control editor edit-select"
          onChange={this.selectRole}
        >
          {this.props.roles.map(name => (
            <option ref={name.id} key={name.id} value={JSON.stringify(role)}>
              {name.title}
            </option>
          ))}
        </select>
      </div>
    );
  }

  selectRole(e) {
    var options = e.target.options;
    var value = [];
    for (var i = 0, l = options.length; i < l; i++) {
        if (options[i].selected) {
            value.push(options[i].value);
        }
    }
    rolesContext._currentValue.selectedRoles = [];
    value.map(value => rolesContext._currentValue.selectedRoles.push(value));
}

export default RolesField;

Context API which i am using to store data.我用来存储数据的上下文 API。

import React from 'react';
export const roles = {selectedRoles: []};
export const rolesContext = React.createContext(roles);



email: "qqq@qqq.com"
id: "507f1f77bcf86cd799439123"
role: []

How can i manage the <select> tag for roles field so that the new inserted record from selected drop down values should be like this:我如何管理roles字段的<select>标记,以便从选定的下拉值中插入的新记录应该是这样的:

{
"id": "507f1f77bcf86cd799439017",
"email": "qqqq@qqqq.com",
"roles": {
  "id": "507f1f77bcf86cd799439123",
  "title": "admin",
  "status": "active"
}
},

PS Please bare with this bit lengthy code. PS请裸露这个有点冗长的代码。

You can break through it by using a map to store the role_id -> role_data pairs.您可以通过使用映射存储 role_id -> role_data 对来突破它。 Assign the role_id as value to each of option, and get the value in the onChange handler.将 role_id 作为值分配给每个选项,并在 onChange 处理程序中获取值。 With this value, you will be able to find the exact role.使用此值,您将能够找到确切的角色。 Then do whatever you need next.然后做你接下来需要的任何事情。

edit: Add sample code编辑:添加示例代码

roles come from eighter state/props角色来自八个状态/道具

const roles = [
  {id: 'id_1', name: 'Admin'},
  {id: 'id_2', name: 'Super Admin'}
]

the onChange handler onChange 处理程序

onChange = e => {
  const id = e.target.value
  const seletedRole = roles.find(role => role.id === id)
  this.setState({
    selectedRole
  })
}

Render select and options渲染选择和选项

<select value={this.state.selectedRole.id} onChange={this.onChange}>
  {
    roles.map(role => <option id={role.id} value={role.id}>{role.name}</option>)
   }
</select>

由于您想通过从列表中选择一个选项来获取整个对象,您可以像这样将整个对象存储为<option> data-value ,您可以将自定义对象替换为data-value

<option data-value='{"name":"abc","status":"active"}'>a</option>

I think you can convert your class component into functional component and using with hooks you can make your life easy.我认为您可以将您的类组件转换为功能组件,并使用钩子可以让您的生活变得轻松。 to use value of context and update the value context have look at this link.要使用上下文的值并更新值上下文,请查看此链接。 How to change Context value while using React Hook of useContext 如何在使用 useContext 的 React Hook 时更改 Context 值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM