我在跟踪<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
答案 0 :(得分:0)
您需要更改:
handleChange={this.onChange}
到
handleChange={handleChange}
这将确保使用Formik
的{{1}}函数。