如何使用react-router v4 Promt

时间:2017-07-03 03:43:01

标签: reactjs react-router

在我的应用程序中,我在不同的页面上有许多表单。如果他们对尚未保存的表单进行了更改,我想向用户添加警告通知。 React router v4似乎在<Promt>中内置了此功能,但是,我已尝试将其放在我的App Router组件中并在表单中,并返回错误ReferenceError: formIsHalfFilledOut is not defined。我该如何正确使用

EG:Wihtin form

render() {
  return (
    <Form className="languageForm" onSubmit={this.handleFormSubmit}>
      <SingleInput inputType={'text'} controlFunc={this.handleLanguageChange(language.uniqueId)} content={language.language} placeholder={'Language'} bsSize={null} error={language.errors && language.errors.language}/>
      <input type="submit" className="btn btn-primary" value="Save"/>
      <Prompt when={formIsHalfFilledOut} message="Are you sure you want to leave?"/>
    </Form>
  );
}

EG:Within App.jsx

const App = appProps => (
  <Router>
    <Prompt when={formIsHalfFilledOut} message="Are you sure you want to leave?"/>
    <NavBar {...appProps}/>
    <Grid className="main-page-container">
      <Switch>
        <Authenticated exact path="/" component={Home} {...appProps}/>
        <Authenticated exact path="/admin/profile_candidate/edit/contact_details" component={ContactDetailsFormContainer} {...appProps}/>
        <Authenticated exact path="/admin/profile_candidate/edit/summary" component={SummaryFormContainer} {...appProps}/>
        <Route render={function() {
          return <p>Page not found</p>;
        }}/>
      </Switch>
    </Grid>
  </Router>
);

1 个答案:

答案 0 :(得分:0)

我认为之所以发生这种情况,是因为你没有宣布你的formIsHalfFilledOut变量。

这个变量的名称(正如我所理解的)被设置为这样,意味着你填写某些表格/字段等时的情况,但是通过链接离开,可能是未完成的。

Codepen示例: https://codepen.io/anon/pen/qxQKOZ

代码:

const {
  HashRouter,
  Switch,
  Route,
  Link, Prompt
} = ReactRouterDOM

class YourForm extends React.Component {
  constructor(){
    super();

    this.state = {
      formIsHalfFilledOut: false,
      value: ''
    }

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event){
    event.preventDefault();

    let value = event.target.value;

    this.setState((prevState)=>{
      let isNotFilled = (value === '');
      return {
          formIsHalfFilledOut: !isNotFilled,
          value: value
      }
    });
  }

  render() {
    const {title} = this.props;

    return (
      <div>
                <Prompt when={this.state.formIsHalfFilledOut} message="Are you sure?"/>
        <h2>{title}</h2>
        <input value={this.state.value} onChange={this.handleChange}/>
        <div>
          <Link to="/">Some link</Link>
        </div>
      </div>
    );
  }
}

ReactDOM.render((
  <HashRouter>
    <YourForm title="I'm the form" />
  </HashRouter>
), document.getElementById('root'))

P.S。 现在可能已经很晚了,但我在研究<Prompt>和东西

时发现了这个问题