【问题标题】:How can i pass data between two classes, components in ReactJS?如何在 ReactJS 中的两个类和组件之间传递数据?
【发布时间】:2019-11-14 14:15:01
【问题描述】:

我有两节课。我想将数据从一个类传递到另一个类。我怎样才能做到这一点?

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


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

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您可以使用以下方式访问 B 类中的数据:

this.props.data

【讨论】:

【解决方案2】:

您的B 组件将获得一个名为data 的道具,您可以在B 组件中使用this.props.data 访问它。

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>
    );

}

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 2017-11-07
    • 2021-11-15
    • 1970-01-01
    相关资源
    最近更新 更多