簡體   English   中英

如何在兩個組件之間傳遞值?

[英]How to pass a value between 2 components?

我有2個單獨的組件,“表單”組件是您輸入名稱的第1步,然后單擊<Link />進入下一步,即“歡迎”組件。

如何將名稱值{this.state.value}從Form組件傳遞到Welcome組件,以便它可以檢索在Form組件中鍵入的內容。

表單組件:

import React from 'react';
import Link from 'react-router';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''      
    };      
  }

  render() {
    return (
      <div className='root'>
        <p>Setup the engine analysation presentation to demo incubation functionality.</p>
        <div className='fieldRow'>
          Name
          <input type="text" autoFocus value={this.state.value} placeholder='Enter Name...'  />
        </div>
        <div className='btnWrapper'>
          <Link to='/welcome' >Access Demo</Link>
        </div>
      </div>
    );
  }
}

export default Form

歡迎組件:

import React from 'react';

class Welcome extends React.Component {
  render() {
    return (
      <div className='root'>
        Welcome <!-- Name Input from Form component -->
      </div>
    );
  }
}

export default Welcome;

你可以像這樣傳遞它

<Link to={{
 pathname: '/welcome',
 state: {
  name: this.state.value
 }
}}>Access Demo</Link>

然后使用withRouter在歡迎頁面(組件)上獲取它

const { location } = this.props;
const name = location && location.state && location.state.name;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM