React—Modal 的确认按钮在 Form 之外,且用到on

2021-07-09  本文已影响0人  krystal_H

react中,Modal 中嵌套Form子组件,提交按钮在 Modal的footer 中(也可用函数组件,本例用 class Component 写的,antd4.x,初次使用react记录一下)

  1. 子组件通过 onRef 绑定实例到父组件
  2. 父组件点击提交去调用子组件的方法

总结:Modal 的确认按钮在 Form 之外,通过 form.submit 方法调用表单提交功能

// 子组件——onRef绑定子组件到父组件
class Child extends Component { 
  formRef = React.createRef() // 在From上绑定ref = {this.formRef}
  componentDidMount() {
   this.props.onRef(this)
  }
// 子组件Form上的onFinish验证通过即调用
  onFinish = (values) => {
    console.log('Success:', values);
  }
}
// 父组件
class Parent extends Component {
  constructor(props) {
    super(props)
    this.refChild = null
  }
  // 创建
  clickNext = (index, e) {
    this.refChild.formRef.current.submit()
  }
  render() {
    return (
      <Modal title="Basic Modal" 
          visible={isModalVisible} 
          onOk={handleOk} 
          onCancel={handleCancel}
          footer={[
          <Button key="previous" onClick={(e) => this.clickPrevious(stepcurrent, e)}>上一步</Button>,
          <Button type="primary" key="next" onClick={(e) => this.clickNext(stepcurrent, e)}>确认创建</Button>]}>
        <div>
          <Child onRef={ref => this.refChild = ref}/>
        </div>
      </Modal>
    )
  }
}
上一篇 下一篇

猜你喜欢

热点阅读