Formik组件内的复选框组

时间:2019-06-21 15:28:36

标签: javascript reactjs formik

我在跟踪<Formik>中的复选框时遇到麻烦。选择架构时,它将呈现适当数量的X复选框。选择一个后,应更新道具值。初始复选框状态位于TableRowWithCheckbox

内部
 export default class TableRowWithCheckbox extends Component {
  constructor(props) {
    super(props);
    const { initialState } = this.props;
    this.state = {
      fieldCheckbox: initialState
    };
  }

  checkbox = () => {
    this.setState({ fieldCheckbox: !this.state.fieldCheckbox }, () => {
      console.log("checkbox --> ", this.state.fieldCheckbox);
      const { name, dataType, position, box } = this.props;
      box({
        name,
        dataType,
        position,
        isChecked: this.state.fieldCheckbox
      });
    });
  };

  render() {
    const {
      name,
      dataType,
      position,
      handleChange
    } = this.props;
    const { fieldCheckbox } = this.state;
    return (
      <React.Fragment>
        <Table.Row>
          <Checkbox
            style={{ marginTop: "20px", marginLeft: "10px" }}
            name="selectedFields"
            checkbox
            onChange={this.checkbox}
          />
          <Table.Cell>{name}</Table.Cell>
          <Table.Cell>{dataType}</Table.Cell>
          <Table.Cell>{position}</Table.Cell>
          <Table.Cell>
            <Input
              onChange={e => handleChange(e, name)}
              value={this.state.size}
              type="number"
              name="size"
              min="1"
              placeholder="1"
              disabled={!this.state.fieldCheckbox}
              required
            />
          </Table.Cell>
          <Table.Cell>
            <Input
              onChange={e => handleChange(e, name)}
              value={this.state.maxArrayElements}
              type="number"
              name="maxArrayElements"
              placeholder="1"
              min="1"
              max="100"
              disabled={!this.state.fieldCheckbox}
              required
            />
          </Table.Cell>
        </Table.Row>
      </React.Fragment>
    );
  }
}

然后在主组件内将TableRowWithCheckbox组件呈现在<Formik>组件内,并带有适当的props。我不确定如何将这个自定义组件连接到Formik。

    <TableRowWithCheckbox
      id={name}
      name={name}
      dataType={dataType}
      value={values.selectedFields}
      position={position}
      initialState={Object.keys(
        selectedFields
      ).includes(name)}
      box={this.checkbox.bind(this)}
      handleChange={this.onChange}
    />
  </React.Fragment>

这里是带有代码的codesandbox

1 个答案:

答案 0 :(得分:0)

您需要更改:

handleChange={this.onChange}

handleChange={handleChange}

这将确保使用Formik的{​​{1}}函数。