ReactJS - ref 不适用于 connect 和 redux-form

ReactJS - ref not working with connect and redux-form

我在通过 connect 和 redux-form 使用 ref 时遇到问题。

组件的结构是 ChildComponent 有表单,我正在使用

class EditEvent extends Component {
  constructor (props) {
    super(props);
    this.handleStartDateChange = this.handleStartDateChange.bind(this);
    this.handleEndDataChange = this.handleEndDataChange.bind(this);
    this.state = {loading: false};
  }

  componentDidMount(){
    this.props.fetchEvent(this.props.session,true);
    this.props.fetchScheduleDates(this.props.session);
  }

  submitSettings(){
    this.props.form.submit();
  }

  handleStartDateChange(date) {
    this.props.updateUnsavedChanges();
    this.props.dateRangeUpdate({startDate:date,endDate:date,allDate:{}});
  }
  handleEndDataChange(date) {
    this.props.updateUnsavedChanges();
    this.props.dateRangeUpdate({startDate:this.props.scheduledates.startDate,endDate:date,allDate:{}});
  }
  renderBlockList(startDate,endDate,allDate){
    /*if(isEmpty(allDate)){
    return 'Please select date duration first.';
  }*/
  var arr = [];
  var day = {};
  var n = endDate.diff(startDate,'days')+1;
  for (var i=1; i <= n; i++ ) {
    if(i !== 1){
      day = moment(day).add(1,'days');
    } else {
      day = startDate;
    }
    var activeDate = _.find(allDate, {scheduledate:moment(day).format('YYYY-MM-DD')});
    arr.push(<DateBlock key={i} day={day} activeDate={activeDate}/>);
  }
  return arr;
}

handleEventName(){
  this.props.updateUnsavedChanges();
}

handleEventDesc(){
  this.props.updateUnsavedChanges();
}

onFormSubmit(values){
  debugger;
  if (this.props.selectedFeatures.length === 0) {
    this.props.showError('Select at least one feature!');
  } else if (values.eventname === '') {
    this.props.showError('Please enter a name');
  } else {
    this.props.submitSettingsHandler(values);
  }
}


render(){
  var eventStartDate = moment();
  var eventEndDate = moment().add(6,'days');
  var isDisabled = false;
  var allDate = [];
  if(this.props.scheduledates.startDate !== undefined){
    eventStartDate = this.props.scheduledates.startDate;
    eventEndDate = this.props.scheduledates.endDate;
    allDate = this.props.allDate;
  }
  if(this.props.scheduledates.isEditable !== undefined){
    isDisabled = true;
  }
  var {handleSubmit, pristine, submitting, invalid} = this.props;
  return(
    <form onSubmit={handleSubmit(this.onFormSubmit.bind(this))} encType="multipart/form-data">
    <div className="general-tab-warp">
      <Field
        name="eventname"
        label="Event name"
        placeholder="E.g google I/O 2017"
        type="text"
        component={this.renderFieldText}
        bsClass="row"
        formdiv="false"
        labelposition={LABEL_POSITION_TOP}
        onChange={this.handleEventName.bind(this)}
      />
      <Field
        name="eventdesc"
        label="Event Description"
        placeholder="Enter event description"
        type="text"
        component={this.renderFieldTextarea}
        bsClass="row"
        formdiv="false"
        labelposition={LABEL_POSITION_TOP}
        onChange={this.handleEventDesc.bind(this)}
      />
      <div className="form-group row">
        <label className="control-label-top col-sm-12">Duration*</label>
        <div className="col-sm-12">
          <Row>
            <Col md={6} style={{width:'48%'}}>
              <DatePicker
                selected = {eventStartDate}
                className = "form-control"
                dateFormat = "DD/MM/YYYY"
                onChange = {this.handleStartDateChange}
                name = "startdate"
                selectsStart
                startDate = {eventStartDate}
                endDate = {eventEndDate}
                minDate = {moment().add(1,'days')}
                disabled={isDisabled}
              />
            </Col>
            <Col md={1} style={{padding:'0px',marginTop:'6px', width:'4%'}}>➔</Col>
            <Col md={6} style={{width:'48%'}}>
              <DatePicker
                selected = {eventEndDate}
                className = "form-control"
                dateFormat = "DD/MM/YYYY"
                onChange = {this.handleEndDataChange}
                name = "enddate"
                minDate = {eventStartDate}
                maxDate = {moment(eventStartDate).add(6, "days")}
                selectsEnd
                startDate = {eventStartDate}
                endDate = {eventEndDate}
                disabled={isDisabled}
              />
            </Col>
          </Row>
          <div className="duration-info">
              * You can't update the date after publishing the app.
          </div>
        </div>
      </div>
      <div className="form-group row">
        <label className="control-label-top col-sm-12">Days</label>
        <div className="col-sm-12">
          <ul className="event-days">
            {this.renderBlockList(eventStartDate,eventEndDate,allDate)}
          </ul>
        </div>
      </div>
      <div className="form-group row">
        <label className="control-label-top col-sm-12">Event Privacy</label>
        <div className="col-md-12">
          <FormGroup>
            <Radio name="event_privacy" inline>
              Public
            </Radio>{' '}
            <Radio name="event_privacy" inline>
              Private
            </Radio>
          </FormGroup>
        </div>
      </div>
  </form>
);
}
}
function mapStateToProps(state){
  return{
    features: state.features,
    session: state.session,
    initialValues: state.eventData[0],
    scheduledates:state.scheduledates,
    allDate:state.updateScheduleDates,
    selectedFeatures: state.selectedFeatures
  };
}

function validate(values) {
  var errors = {};
  if (values['eventname'] === '') {
    errors['eventname'] = 'Event name is required';
  }
  return errors;
}

export default connect(mapStateToProps,{fetchEvent,updateUnsavedChanges,fetchScheduleDates,dateRangeUpdate,patchEventDetails,showError,showSuccess},null,{withRef:true})(reduxForm({
  validate,
  form:'EditEventForm',
  enableReinitialize: true,
  keepDirtyOnReinitialize: true
})(EditEvent));

组件有功能

submitSettings(){
  this.props.form.submit();
}

我想从父组件调用 submitSettings,我在其中使用 ref,见下文

constructor(props){
    super(props);
    this.editEventRef = React.createRef();
  }

onSaveClick(){
 this.editEventRef.current.submitSettings();
}

render(){
    return(
       <EditEvent ref={this.editEventRef}/>    
    )
 }

当调用 onSaveClick 时,我总是得到以下错误

Uncaught TypeError: this.editEventRef.current.submitSettings is not a function

当我更改以下行并删除 [=16= 中 reduxForm() 的使用时,错误出现并且函数工作正常]

export default 
connect(mapStateToProps,
{fetchEventDetails}
,null,{withRef:true})(EditEvent);

谁能指导我解决这个问题?我错过了什么吗?

感谢您的帮助。

更新 这些是我正在使用的软件包的 npm 版本,如果有帮助的话。

"react": "^16.7.0" "react-dom": "^16.7.0", "react-redux": "^5.1.1", "redux-form": "^6.7.0",

好的,所以在花了这么多时间之后我找到了解决方案,这适用于 "react":“^16.7.0”"redux-form": "^8.1.0" 现在是最新的。

当你像我在问题中那样使用connect() reduxForm()时,你需要使用

this.editEventRef.current.wrappedInstance.submitSettings();

因此,只要子组件中有 reduxForm,就需要使用 .current.wrappedInstance 来访问回调,否则使用 .current 仅。

您需要使用 {forwardRef:true} 作为 connect()

中的选项

虽然我没有在任何地方找到它的文档,但上面的作品。

希望对寻找类似答案的人有所帮助。

干杯。