简体   繁体   English

如何在两个组件之间传递值?

[英]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. 我有2个单独的组件,“表单”组件是您输入名称的第1步,然后单击<Link />进入下一步,即“欢迎”组件。

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. 如何将名称值{this.state.value}从Form组件传递到Welcome组件,以便它可以检索在Form组件中键入的内容。

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 然后使用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