背景
其实Handsontable官方也提供了React的版本,但是官方的版本再编辑和渲染的时候并不能够很好的嵌入第三方的组件库。这就导致了,使用了Handsontable就没有办和普通的react项目一样轻松引用其他第三方组件。因此对其react的版本进行了二次的封装,使其可以轻松的兼容第三方组件库。
Demo
git:GitHub - JavonHuang/jv-react-handsontable
安装
npm i @javonhuang/rh-table
引用
import { RHTable } from "@javonhuang/rh-table";
import '@javonhuang/rh-table/style'
数据渲染
const ScoreRenderer = (props:any) => {
const { value } = props;
const color = value > 60 ? '#2ECC40' : '#FF4136';
return (
<span style={{ color }}>我的分数:{value}</span>
);
};
{
title:"分数",
dataIndex: "score",
readOnly: false,
validator: (e) => {
return new Promise((resolve) => {
if (e >= 60) {
resolve(true)
} else {
resolve(false)
}
})
},
renderCell: (e) => {
return <ScoreRenderer {...e}></ScoreRenderer>
},
},
数据编辑
单选
多选、必填列
const CitySelect = (e:any) => {
const [options, setOptions] = useState<Array<any>>([])
useEffect(() => {
setTimeout(() => {
setOptions(countryList)
}, 1000);
}, [])
const change = (res:any) => {
e.change(res,true)
}
return <Select options={options} defaultValue={e.value} onChange={ change}></Select>
};
const HobbySelect = (e: any) => {
const defaultValue=e.value
const [options, setOptions] = useState<Array<any>>([])
useEffect(() => {
setTimeout(() => {
setOptions(hobbyList)
}, 1000);
}, [])
const change = (res:any) => {
e.change(res)
}
return <Select mode="multiple" options={options} defaultValue={defaultValue} onChange={ change}></Select>
};
{
title:"国家(单选)",
dataIndex: "country",
editorCell: (e) => {
return <CitySelect {...e}></CitySelect>
},
renderCell: (e) => {
return getlable(countryList,e.value)
}
},
{
title:"爱好(多选)",
dataIndex: "hobby",
width: 120,
editorCell: (e) => {
return <HobbySelect {...e}></HobbySelect>
},
required: true,
validator: (e) => {
return new Promise((resolve) => {
if (e&&e.length==0) {
resolve(false)
} else {
resolve(true)
}
})
}