如何使动态复选框和使用提取帖子发布数据?

时间:2019-01-21 07:36:52

标签: reactjs post checkbox event-handling fetch

我有一个包含此数据的常量文件:

export let testing= [
  { id: 'test1', label: 'Test1' },
  { id: 'test2', label: 'Test2' },
  { id: 'test3', label: 'Test3' }
]

在我的checkboxes.js中,

class CheckBoxes extends Component {
  constructor(props) {
    super(props);
    this.state = ({
      checkBoxArray: [],
      isChecked: false 
    })
  }

  handleSubmit = (event) => {
    event.preventDefault();     //use for testing only
   fetch(`${process.env.REACT_APP_SERVER_URL}/testing`, {
      method: "POST",
     headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        check_box_data: event.target.check_box_name[].value,   //error
      })
    })
      .then(response => {
        console.log(response);
        if (response.status === 200) {
          console.log('Success')
        } else {
          alert('Failed')
        }
      })
      .catch(error => {
        alert('Server error')
      });
  }

  handleCheckBoxChange = (index) => {     //not working
    const {checkBoxArray} = this.state;

    checkBoxArray[index].checked = !checkBoxArray[index].checked;
    this.setState({           //this line causes maximum depth mount error
      checkBoxArray
  });
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
           <div>
                {
                  this.state.checkBoxArray.map((object, index) => {
                    return (
                      <CheckBoxComponent
                        key={index}
                        check_box_id={object.id}
                        check_box_name='check_box_name[]'
                        check_box_label={object.label}
                        check_box_value={object.id}
                        isChecked={this.state.isChecked}
                        handleCheckBoxChange={this.handleCheckBoxChange(index)}
                      />
                    );
                  })
                }

            <SingleButtonComponent button_type='submit' button_value='Create Now' />
          </div>
        </form>
      </div>

    )
  }
}

export default CheckBoxes;

在我的复选框组件js中:

import React from 'react';

const CheckBoxComponent = (props) => {
  const { check_box_id, check_box_name, check_box_label, check_box_value, isChecked, handleCheckBoxChange } = props;
  return (
    <div>
      <input type='checkbox' id={check_box_id} name={check_box_name} value={check_box_value} checked={isChecked} onChange={handleCheckBoxChange}/>
      <label htmlFor={check_box_id} className='lh-copy'>&nbsp;{check_box_label}</label>
    </div>
  )
}
export default CheckBoxComponent;

我的第一个问题是我无法将复选框值发布为获取api中的数组。显然event.target.check_box_name[].value中不允许[]。我尝试做event.target.check_box_name.value,但返回的值无法读取未定义的属性“值”。我想将复选框值的数组发送回服务器。

第二个问题是我不知道如何设置动态生成的复选框。这段代码将选中所有复选框。我只在常数文件中显示3行数据,而且它不止于此,所以我将不接受任何静态工作的解决方案。

如果您需要我添加更多详细信息或其他内容,请告诉我。谢谢你。

2 个答案:

答案 0 :(得分:1)

请勿在渲染handleCheckBoxChange()中直接调用函数,请使用=>或为此进行绑定:

class CheckBoxes extends Component {
    constructor(props) {
      super(props);
      this.state = ({
        checkBoxArray: [  { id: 'test1', label: 'Test1' },
        { id: 'test2', label: 'Test2' },
        { id: 'test3', label: 'Test3' }],
        isChecked: false 
      })
    }

    handleSubmit = (event) => {
      event.preventDefault();     //use for testing only
     fetch(`${process.env.REACT_APP_SERVER_URL}/testing`, {
        method: "POST",
       headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          check_box_data: event.target.check_box_name.value,   //error
        })
      })
    }

    handleCheckBoxChange = (id) => {
      const checkBoxArray = [...this.state.checkBoxArray];
      const index = checkBoxArray.findIndex(object => object.id === id);
      checkBoxArray[index].isChecked = !checkBoxArray[index].isChecked;
      this.setState({
        checkBoxArray
      });
    }

    render() {
      return (
        <div>
          <form onSubmit={this.handleSubmit}>
             <div>
                  {
                    this.state.checkBoxArray.map((object, index) => {
                      return (
                        <CheckBoxComponent
                          key={object.id}
                          check_box_id={object.id}
                          check_box_name='check_box_name'
                          check_box_label={object.label}
                          check_box_value={object.id}
                          isChecked={object.isChecked}
                          handleCheckBoxChange={this.handleCheckBoxChange} //you can pass id here but affect performance
                        />
                      );
                    })
                  }

            </div>
          </form>
        </div>

      )
    }
  }



const CheckBoxComponent = (props) => {
  const { check_box_id, check_box_name, check_box_label, check_box_value, isChecked, handleCheckBoxChange } = props;
  return (
    <div>
      <input type='checkbox' id={check_box_id} name={check_box_name} value={check_box_value} checked={isChecked} onChange={() => {handleCheckBoxChange(check_box_id)}}/>
      <label htmlFor={check_box_id} className='lh-copy'>&nbsp;{check_box_label}</label>
    </div>
  )
}

CheckBoxComponent.defaultProps = {
  isChecked: false,
}

export default CheckBoxComponent;

答案 1 :(得分:0)

hecked param复选框取决于记录为this.state.isChecked的道具ishecked,并且从不更改。

为什么?

每个复选框都相同?

将检查的条件更改为

<CheckBoxComponent
   key={index}
   // ... some props
   isChecked={object.checked} // you update this field in handleCheckBoxChange
/>