我想在react中创建带有子组件的自定义表,但我无法实现
这是我的代码
import React from 'react';
const DataTableContext = React.createContext();
const Header = () => {
return (
<DataTableContext.Consumer {...props}>
<thead>{props.children}</thead>
</DataTableContext.Consumer>);
}
const Row = (props) => {
return (
<DataTableContext.Consumer>
<tr>{props.children}</tr>
</DataTableContext.Consumer>);
}
const Cell = (props) => {
return (
<DataTableContext.Consumer>
<td style={{ width: props.width }}>{props.children}</td>
</DataTableContext.Consumer>);
}
const Body = (props) => {
return (
<DataTableContext.Consumer>
<tbody>{props.children}</tbody>
</DataTableContext.Consumer>);
}
const DataTable = props => {
return (
<DataTableContext.Provider {...props}>
<table className="bordered">{props.children}</table>
</DataTableContext.Provider>
);
}
DataTable.Header = Header;
DataTable.Row = Row;
DataTable.Cell = Cell;
DataTable.Body = Body;
export default DataTable
有什么办法可以解决我的问题? 我还引用了以下文章: https://medium.com/maxime-heckel/react-sub-components-part-2-using-the-new-context-api-6f1c089acfe4
答案 0 :(得分:0)
正确使用Context.Consumer
的方式,以您的Cell
为例:
const Cell = ({ width, children }) => (
<DataTableContext.Consumer>
{(value) => <td style={{ width }}>{children}</td>}
</DataTableContext.Consumer>
);
我建议您像这样使用useContext
而不是Consumer
:
const Cell = ({ width, children }) => {
const context = useContext(DataTableContext);
return <td style={{ width }}>{children}</td>;
};
如果只想自定义表而不传递数据,则不需要Context
API。