2017-07-08 46 views
0

我想创建一组复选框,选择创建一个包含多个字段的对象数组。每当我在这里选择一个复选框时,它会出现错误并要求输入密钥。我有一把钥匙,所以我有点困惑。复选框选择创建一个数组

路径:Form Component

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

    this.state = { 
     rolesInterestedIn: [], 
    }; 

    this.handleRoleTypeSelection = this.handleRoleTypeSelectionTwo.bind(this); 
    } 


    handleRoleTypeSelection(evt){ 
    evt.preventDefault(); 

    this.setState({ 
     rolesInterestedIn: [{ 
     roleType: evt.target.value, 
     yearsOfExpereince: '' 
     }] 
    }) 
    } 

    render() { 
    return (
     <div className="paper"> 
     <Form className="roleAndSkillsForm" onSubmit={this.handleFormSubmit}> 
      <CheckboxGroupTwo 
      name={'typeOfWork'} 
      options={['Audit - internal', 'Audit - external', 'Tax']} 
      label={'What roles are you most interested in? *'} 
      controlFunc={this.handleRoleTypeSelection} 
      /> 
     </Form> 
     </div> 
    ); 
    } 
} 

路径:Checkboxgroup Component

const CheckboxGroup = (props) => (
    <FormGroup controlId={props.name}> 
    {props.options.map(opt => { 
     console.log(opt); 
     return (
     <Checkbox 
      name={props.name} 
      key={opt} 
      onChange={props.controlFunc} 
      value={opt} 
      checked={opt.selectedOption} 
      inline 
     > 
      {opt} 
     </Checkbox> 
     ); 
     })} 
    </FormGroup> 
); 

    CheckboxGroup.propTypes = { 
    name: PropTypes.string, 
    options: PropTypes.array, 
    selectedOption: PropTypes.string, 
    controlFunc: PropTypes.func, 
    label: PropTypes.string 
    }; 

回答

0

当使用给定的阵列上使用的索引参数,并将它们传递到密钥属性映射方法。

例如;

const array = ['food', 'drinks', 'clothes']; 
array.map((item, index) => { 
    <li key={index}>{item}</li> 
}); 

当你没有稳定的ID为渲染的项目,你可以使用 项指标作为一个关键的最后一招:

const todoItems = todos.map((todo, index) => 
    // Only do this if items have no stable IDs 
    <li key={index}> 
    {todo.text} 
    </li> 
); 

有关密钥的详细信息和列表参考Lists and Keys - React

+0

我读过。我不确定使用索引复选框是否正常,或者是否应该以某种方式避免它。 – bp123