鍍金池/ 問答/HTML/ react 我想把子組件的表單提交給父組件 但是一直獲取不到

react 我想把子組件的表單提交給父組件 但是一直獲取不到

這是我父組件里調(diào)用的子組件

 modalCancel = () => {
    this.setState({
      modalVisible: false,
    })
  }
  modalHandleOk = () => {
    this.setState({
      modalVisible: false,
    })
  }
  saveFormRef=(form)=>{
    console.log(form)
  }


            <LeisurePriceStockAddModal
              ref={this.saveFormRef}
              modalVisible={this.state.modalVisible}
              modalCancel={this.modalCancel}
              modalHandleOk={this.modalHandleOk}
            />

這是子組件

import React from 'react'
import {Form ,Modal,Input,Button} from 'antd'
// import InputCom from '../../../../../../../components/tableCom/InputCom'
const FormItem = Form.Item
class LeisurePriceStockAddModal extends React.Component {
  render (){
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
    };
    const {modalVisible,modalCancel,modalHandleOk,form} = this.props
    const {getFieldDecorator} = form
    return (
      <Modal
        visible={modalVisible}
        title={"添加套餐"}
        onCancel={modalCancel}
        onOk={modalHandleOk}
      >
        <Form layout='horizontal'>
          <FormItem {...formItemLayout} label={'套餐名稱'}>
            {getFieldDecorator('套餐',{
              rules: [{required: true, message: '套餐名稱不能為空'}],
              initialValue: '',
            })(
              <Input/>
            )}
          </FormItem>
        </Form>
      </Modal>
    )
  }
}
export default Form.create()(LeisurePriceStockAddModal)

form一直獲取不到是什么情況 請大佬幫我看看

回答
編輯回答
別傷我

謝邀!
父組件獲取子組件的數(shù)據(jù)呢,一般有兩種方法。

  • refs

子函數(shù)定義一個方法 getValues = () => {return value},然后父組件通過refs獲?。?/p>

<SubComponent ref={ref => this.subComponent = ref}/>
// other code

() => {
    const value = this.subComponent.getValues();
    // value 就是子組件返回的數(shù)據(jù)
}
  • 回調(diào)函數(shù)

父組件:

const setValues = (value) => {
    //value 就是子組件傳回的數(shù)據(jù)
}

<SubComponent setValues={setValues}/>

子組件

const {setValues} = this.props
<button onClick={() => {
    setValues(value); //value 就是子組件需要傳到父組件的數(shù)據(jù)
}}>Submit</button>

一般建議使用第二種,因為我們再更多的使用是stateless的方式,而stateless不支持refs。

2018年6月5日 22:09
編輯回答
柚稚
constructor(props) {
    super(props);
    props.ref(props.form);
}

在子組件加這個

2017年4月30日 09:57