【问题标题】:How to pass component as props with props in react?如何将组件作为道具传递给反应中的道具?
【发布时间】:2018-06-04 08:57:35
【问题描述】:

我正在使用来自 dev-express 的 react-grid 库, 库中有一个 Table 组件,我们可以将 Cell 组件传递给它, 在 CustomCell 中,我正在使用 Material UI 中的菜单

  <Table
        columnExtensions={tableColumnExtensions}
        cellComponent= {CustomCell}
  />

在上述情况下菜单工作正常,

但我想将道具传递给这个组件,我尝试了以下

 <Table
        columnExtensions={tableColumnExtensions}
        cellComponent= {(props)=><CustomCell {...props} someFunc={this.someFunc} />}
/>

在这种情况下,菜单不起作用,我想知道是否有其他方法可以实现第二种情况。

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    您可以使用withProps

    const CustomCellWithSomeFunc = withProps({someFunc: this.someFunc.bind(this)})(CustomCell);
    
    <Table
        columnExtensions={tableColumnExtensions}
        cellComponent= {CustomCellWithSomeFunc/>}
    />
    

    【讨论】:

    • 感谢您的回答,但我也想从 Table Component 中获取道具以及我定义的其他道具,
    【解决方案2】:

    鉴于您周围的组件提供了props,您可以这样:

    class Foo extends React.Component {
    
      someFunc = () => {}
    
      render () {
        return <Table
          columnExtensions={tableColumnExtensions}
          cellComponent= {() => <CustomCell {...this.props} someFunc= 
            {this.someFunc} />}
          />
      } 
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 1970-01-01
      • 2017-01-31
      • 2019-07-29
      • 1970-01-01
      • 2020-05-25
      • 2017-08-17
      • 2019-01-27
      相关资源
      最近更新 更多