简体   繁体   中英

How to pass a value between 2 components?

I have 2 separate components, Form component is the step 1 where you enter your name, then by clicking <Link /> you go to the next step which is Welcome component.

How can I pass the name value {this.state.value} from Form component to Welcome component so it can retrieve what was typed in the Form component.

Form component:

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

Welcome component:

import React from 'react';

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

export default Welcome;

You can pass it as state like this

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

Then get it on welcome page (component) using withRouter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM