【问题标题】:Adding additional props to a component passed as a prop向作为道具传递的组件添加额外的道具
【发布时间】:2018-10-14 05:14:26
【问题描述】:

我在 react-redux 应用程序中使用 React TableReact Custom Scrollbars。要连接这两者,我需要覆盖 React 表中的 TbodyComponent ,这样我就可以用滚动条包装默认的 tbodycomponent 并传递额外的道具来调整渲染。这是一些精简的代码:

import React from 'react'
import ReactTable from 'react-table'
import {ReactTableDefaults} from 'react-table'
import { Scrollbars } from 'react-custom-scrollbars'

const TableBody = props => {
    //get additional props beyond just props.children here
    const {autoHeight} = props

    return (
        <Scrollbars 
            style={{
                height: '100vh'
            }}
        >
            <ReactTableDefaults.TbodyComponent>
                 {props.children}
            </ReactTableDefaults.TbodyComponent>
        </Scrollbars>
    )
}


const Table = props => {
    //props stuff would go here

    return (
            <div className="react-table-wrapper">
                <ReactTable {...props}
                            TbodyComponent={TableBody} //this works
                            //TbodyComponent={(props) => {return (<TableBody autoHeight={props.autoHeight} children={props.children} />)}} //this doesn't
                            data={data}
                            columns={columns}
                            ...
                />
            </div>
    )
}

我猜我不理解在 TbodyComponent 属性、props.children 或类似内容中传递组件的正确方法。这种方法最终会永远循环下去。

在这个例子中,我怎样才能让 autoHeight 属性通过?

更新:尝试使用 createElement 和 cloneElement 仍然收到 130 错误。

【问题讨论】:

    标签: reactjs react-table


    【解决方案1】:

    试试这个

    <ReactTable TbodyComponent={v => <DropTbody test={null} />} 
    

    【讨论】:

    • 以下是How do I write a good answer? 的一些指南。提供的这个答案可能是正确的,但它可以从解释中受益。仅代码答案不被视为“好”答案。
    【解决方案2】:

    解决这个问题的方法是将TableBody无状态组件转换为完整组件,即

    class TableBody extends React.Component {
    

    而不是

    const TableBody = props => {
    

    这正是 React-Table 所期待的。

    【讨论】:

      【解决方案3】:

      这有什么不可行的原因吗?

      TbodyComponent={<TableBody autoHeight={props.autoHeight} />}
      

      另外,我认为您不需要传递 props.children - 默认情况下应该这样做。

      作为参考,我查看了此处提供的类似问题的答案:https://stackoverflow.com/a/39655113/8060919

      【讨论】:

      • 尝试过并收到以下 React 错误:“元素类型无效:应为字符串(用于内置组件)或类/函数(用于复合组件)但得到:对象。”
      • 您是否检查过以确保您正确执行所有导入操作?见stackoverflow.com/questions/34130539/…。你可能会在不应该的时候导入带括号的组件。
      猜你喜欢
      • 1970-01-01
      • 2018-09-24
      • 2018-08-01
      • 2019-05-12
      • 2020-03-22
      • 2021-09-08
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      相关资源
      最近更新 更多