【问题标题】:Multiple instances of react component: access propreact组件的多个实例:access prop
【发布时间】:2019-01-18 00:34:06
【问题描述】:

我想拥有两个具有不同文本并且可以将不同参数传递给操作的组件,但我想重用它们。

我有父类“保险”,相关部分(imo)是这个。

render() {
  return (
    <InsuranceTypeCard
      type="HOUSEHOLD_GOODS"
      header="myThings"
    />
    <InsuranceTypeCard
      type="PRIVATE_LIABILITY"
      header="myDamages"
    />
  )
}

现在在 InsuranceTypeCard 中,我使用这样的道具,它以不同的方式呈现类型两次,但在“对话框”(来自 material-ui 的弹出窗口)中,它只会呈现第二种类型两次,所以看起来因为它们以某种方式共享相同的道具,并且第二个组件覆盖了第一个实例。

//insuranceTypeCard.tsx
render() {
  return (
    <div>
      {this.props.type}
    </div>
    <Dialog>
      {this.props.type};
    </Dialog> 

【问题讨论】:

标签: reactjs


【解决方案1】:

你可以试试这个吗?

import React, { Fragment } from 'react';

// further down in your code...
render() {
  return (
    <Fragment>
      <InsuranceTypeCard
        type="HOUSEHOLD_GOODS"
        header="myThings"
      />
      <InsuranceTypeCard
        type="PRIVATE_LIABILITY"
        header="myDamages"
      />
    </Fragment>
  );
}

当您尝试并排渲染组件时,可以使用&lt;Fragment&gt; 组件。但是,它只是在 React 16.2 中添加的,所以如果你运行的是以前的版本,你可以像这样 polyfill 功能:

const Fragment = ({ children }) => children;

// the rest is the same

看看有没有帮助。

【讨论】:

  • 感谢您的建议。但似乎并没有改变什么。奇怪的是第一个 {this.props.type} 会返回正确的不同类型,但在对话框中它不再工作了
  • 现在我通过将当前打开的对话框的名称存储在 redux 存储中,然后将 mapStateToProps 存储到新的道具来解决它。
  • @solaire 这真的很奇怪。你可以使用 Chrome/Firefox 中的 React devtools 扩展来检查哪些 props 被传递到你的 React 组件中;看看有没有帮助?
猜你喜欢
  • 2018-12-02
  • 2023-03-23
  • 1970-01-01
  • 2022-10-26
  • 2018-05-21
  • 2021-04-08
  • 2020-03-28
  • 2019-05-27
  • 1970-01-01
相关资源
最近更新 更多