简体   繁体   English

如何在 ReactJS 中的两个类、组件之间传递数据?

[英]How can i pass data between two classes, components in ReactJS?

I have two classes.我有两节课。 I want to pass data from one class to another.我想将数据从一个 class 传递到另一个。 How can I achieve that?我怎样才能做到这一点?

class A extends React.Component {
  render() {
    return (
      <B  data={this.getData()} />
    );
  }
}


class B extends React.Component {
    //How can i consume "data" in here?
}

You can access the data in class B using:您可以使用以下命令访问 class B 中的数据:

this.props.data

Your B component will be given a prop called data which you can access with this.props.data within your B component.您的B组件将获得一个名为data的道具,您可以在B组件中使用this.props.data访问该道具。

https://reactjs.org/tutorial/tutorial.html#passing-data-through-props https://reactjs.org/tutorial/tutorial.html#passing-data-through-props

class A extends React.Component {
  getData() {
    return [ { "test": "data" } ];
  }

  render() {
    return (
      <B  data={this.getData()} />
    );
  }
}


class B extends React.Component {
  render() {
    return (
      <label>test: <span>{this.props.data['test']}</span></label>
    );

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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