如何在React js中将状态从一个组件传递到另一个组件?

Hem*_*ath 0 javascript state reactjs

我有下面的组件,它有4个状态值

class ComposedTextField extends React.Component {
  state = {
    name: '',
    title: '',
    email: '',
    experience: ''
  };

  handleChange = event => {
    this.setState({ 
          [event.target.name]:event.target.value,
          [event.target.title]:event.target.value,
          [event.target.email]:event.target.value,
          [event.target.experience]:event.target.value
        });
  };

  render() {
    const { classes } = this.props;

    return (
      <div>
        <Typography variant="headline">Header Info</Typography>
        <FormControl fullWidth className={classes.formControl}>
          <InputLabel htmlFor="name-simple">Name</InputLabel>
          <Input name="name" value={this.state.name} id="name-simple" onChange={this.handleChange}/>
        </FormControl><br></br>
        <FormControl fullWidth className={classes.formControl}>
          <InputLabel htmlFor="title-simple">Title</InputLabel>
          <Input name="title" id="title-simple" value={this.state.title} onChange={this.handleChange}/>
        </FormControl><br></br>
        <FormControl fullWidth className={classes.formControl}>
          <InputLabel htmlFor="email-simple">Email</InputLabel>
          <Input name="email" id="email-simple" value={this.state.email} onChange={this.handleChange}/> 
        </FormControl><br></br>
        <FormControl fullWidth className={classes.formControl}>
          <InputLabel htmlFor="experience-simple">Experience</InputLabel>
          <Input name="experience" id="experience-simple" value={this.state.experience} onChange={this.handleChange}/>
        </FormControl><br></br>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我需要将这4个值传递到另一个组件中

function Header(props) {
  const { classes, avatar } = props;
  return (
    <div>
              <Typography variant="headline">KASUN FERNANDO</Typography>
              <Typography variant="subheading" color="textSecondary">
              SENIOR DESIGNER-UI/UX
              </Typography>
              <Typography variant="subheading" color="textSecondary">
              mickey@crowderia.com
              </Typography>
              <Typography variant="subheading" color="textSecondary">
              4+ years of experience
              </Typography>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

在此组件中,有4种印刷术,我需要在4种印刷术中显示该状态值

我该怎么做,请帮助我成为React js的新手

Ase*_*tam 7

有很多非终极版,mobx,对如何管理/传递部件之间的状态通量策略- ,,Props 等,你可以阅读这篇文章的组件通信。在使用重量级状态管理框架之前,您可能需要看一下这些内容。Instance MethodsCallbacks

反应组件通信

从给出的代码中,我假设标头是更高级别的组件。对于孩子与父母的沟通,您可以利用callback functions

父母会将一个函数作为道具传递给孩子,如下所示:

<MyChild myFunc={this.handleChildFunc} />
Run Code Online (Sandbox Code Playgroud)

然后孩子会像下面这样调用该函数:

this.props.myFunc();
Run Code Online (Sandbox Code Playgroud)