6

ref一起使用via connect 和 redux-form时遇到问题。

组件的结构使得ChildComponent具有 Forms 并且我正在使用

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%'}}>➔&lt;/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();
}

我想从使用ref的 Parent 组件调用submitSettings,见下文

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

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

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

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

未捕获的 TypeError:this.editEventRef.current.submitSettings 不是函数

当我更改以下行并删除reduxForm()in的使用时,错误发生并且功能正常connect()

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”,

4

1 回答 1

5

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

当您使用connect() reduxForm()我在问题中所做的方式时,您需要使用

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

因此,每当子组件中有 reduxForm 时,您需要使用.current.wrappedInstance来访问回调,否则仅使用.current

您需要在connect(){forwardRef:true}中使用as 选项

我没有发现它在任何地方都有记录,但上面的作品。

希望它可以帮助寻找类似答案的人。

干杯。

于 2019-01-22T18:16:19.483 回答