React,focus()触发提交

时间:2017-12-04 11:18:31

标签: reactjs routes

我有路线:

export const Routes = (props) => {
  return(
//----------
<Switch>
        <Route exact path='/:id' render={props => <AdvFormEditContainer/>}/>
        <Route path='/' render={props => <Main/>}/>
</Switch>
//----------
    )
}

<AdvFormContainer/>内有<Main/>

export class AdvFormContainer extends React.Component {
  constructor(props) {
    super(props);
    this.submitForm = this.submitForm.bind(this);
    this.onChange = this.onChange.bind(this);
    this.state = {
      titleError: '',
      textError: ''
    }
  }

  componentDidMount() {     // Comment it out and no titleError message
    this.focusForm.focus(); 
  }

  onChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    })
  }

  submitForm(e) {
    e.preventDefault();
    const {title, text} = this.state;
    const {logged, addAdv} = this.props;
    const author = logged[0].name;
    if (title && text) {
      addAdv(author, title, text);
      setTimeout(() => {
        this.setState({
          title: '',
          text: ''
        })
      }, 2000);
      this.resetForm.reset();
    } else if (!title) {  // Get fired because there is no title yet!
      this.setState({
        titleError: 'Please, enter title!'
      });
      setTimeout(() => {
        this.setState({
          titleError: ''
        })
      }, 2000);
    } else if (!text) {
      this.setState({
        textError: 'Please, enter the text!'
      });
      setTimeout(() => {
        this.setState({
          textError: ''
        })
      }, 2000);
    }

  }

  render() {
      return (
  <div>
    <AdvForm
  {...this.props}
  onChange={this.onChange}
  submitForm={this.submitForm}
  resetRef={el => this.resetForm = el}
  focusRef={el => this.focusForm = el}
  titleError={titleError}
  textError={textError}
  />
  </div>
)
  }
}

<AdvForm>组件:

export const AdvForm = (props) => {
  const {......., resetRef, focusRef} = props;
  return (<form action="post"
    ref={resetRef}
    >
                            <MuiThemeProvider>
                              <TextField
    ref={focusRef}
    //---------------------
    />


                     </MuiThemeProvider>
//----------------------                      
                    </form>)}

第一次安装<Main/><AdvFormContainer/>时,一切正常。 但是,如果路径从path="/:id"更改为path="/",则<AdvForm/>内部 <AdvFormContainer/>以空inputs提交,会触发错误消息。 出现这种行为是因为

componentDidMount() {     // Comment it out and no titleError message
    this.focusForm.focus(); 
  }

如果没有focus(),则没有空提交。 <Button/>与此无关。我试图从onSubmit中取出<Button/>并将其附加到<form>。同样的行为。

出于好奇,请发生什么事?

0 个答案:

没有答案