2017-07-03 66 views
1

在我的應用程序中,我在不同的頁面上有許多表單。如果用戶對未保存的表單進行了更改,我希望向用戶添加警報通知。 React路由器v4似乎有內置<Promt>這個功能,但是,我試過把它放在我的App Router組件和表格內,它返回一個錯誤ReferenceError: formIsHalfFilledOut is not defined。如何使用這個正確如何使用react-router v4 Promt

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> 
); 

回答

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>和東西時發現了這個問題