听起来您正在寻找高阶组件 (HOC) - React 中用于重用组件逻辑的技术。HOC 不是 React API 的一部分,而是从 React 的组合特性中出现的一种模式。
在这种情况下,您想使用一些常见的props
. 实现此目的的一种选择是使用ReCompose library及其withProps
方法。这是一个例子:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { withProps } from "recompose";
import ReactTable from "react-table";
const CommonTable = withProps({
className: '-striped -highlight mb-3',
multisort: true,
showPagination: false,
resizable: false,
etc: etc
})(ReactTable);
此外,在将 ReactTable 与 HOC 结合使用时,似乎需要注意一些因素,如docs中所述。
这是一个例子:
const { withProps } = Recompose;
const CommonTable = withProps({
className: '-striped -highlight mb-3',
multisort: true,
showPagination: false,
resizable: false
})(ReactTable.default);
const data = [
{
name: 'Tanner Linsley',
age: 26,
friend: {
name: 'Jason Maurer',
age: 23,
}
}
];
const columns = [
{
Header: 'Name',
accessor: 'name' // String-based value accessors!
}, {
Header: 'Age',
accessor: 'age',
Cell: props => <span className='number'>{props.value}</span> // Custom cell components!
}, {
id: 'friendName', // Required because our accessor is not a string
Header: 'Friend Name',
accessor: d => d.friend.name // Custom value accessors!
}, {
Header: props => <span>Friend Age</span>, // Custom header components!
accessor: 'friend.age'
}
];
ReactDOM.render(<CommonTable data={data} columns={columns} />, document.getElementById("app"));
<link href="https://cdnjs.cloudflare.com/ajax/libs/react-table/6.7.6/react-table.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/recompose/0.26.0/Recompose.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-table/6.7.6/react-table.js"></script>
<div id="app"></div>