将状态从一个React组件传递到另一个

时间:2018-05-14 09:51:10

标签: javascript reactjs properties

我是React的新手(3天经验)

我想将一个日期从一个组件传递到另一个组件,但这对我不起作用。

到目前为止我实施的内容:

export class Kurse extends React.Component {
constructor(props) {
  super(props);
}


numbers = ["21.02.2019", "02.05.2018", "13.03.2018", "04.07.2018", "05.08.2018"];
listItems = this.numbers.map((date) =>
  <p><Link to={{pathname: "/bookCourse/"+date}}><Button>{date}</Button></Link></p>
);
render() {
  return(
    <div>
      <h2>Wähle Deinen Wunschtermin</h2>
      {this.listItems}
    </div>
  );
 }
} 
ReactDOM.render(
  <BrowserRouter>
      <Switch>
          <Route path="/" exact render = { () => <Home/>} />
          <Route path="/cityChoice" exact render = { () => <CityChoice/>} />
          <Route path="/kurse" exact render = { () => <Kurse/>}/>
          <Route path='/kjhkhkhkh-spezialisten' component={() => window.location = 'http://kjhkhkhkh-spezialisten.de'}/>
          <Route path='/bookCourse/:date' exact render = { () => <Form/>} />            
      </Switch>
  </BrowserRouter>,
  document.getElementById('root')
)
export class Form extends React.Component{
  constructor(props){
    super(props);

    this.state = {
        vorname: '',
        nachname: '',
        email: '',
        telefon: '',
        refbeginn: 'nächstes Jahr',
        schulart: 'grundschule'
    };
}

...
...

return (
    <div id="form_container">
     {this.props.location.params.date}
...
...

我的期望:

我希望可以从Form组件中访问日期变量。

实际结果:

TypeError:this.props.location未定义

1 个答案:

答案 0 :(得分:2)

您应该将props传递给组件以在组件内部访问它。在你提到的情况下

<Form location = "some value" />

这允许您使用{this.props.location}来访问Form组件一侧的位置道具。

相关问题