Redux example

优质
小牛编辑
135浏览
2023-12-01

An implementation of the @handsontable/react component with a readOnly toggle switch and the Redux state manager implemented.

import React from 'react'; import ReactDOM from 'react-dom'; import {createStore, combineReducers} from 'redux'; import {HotTable} from '@handsontable/react'; import Handsontable from 'handsontable'; const initialReduxStoreState = { data: Handsontable.helper.createSpreadsheetData(5, 3), colHeaders: true, rowHeaders: true, readOnly: false }; // Action reducers for callbacks triggered by Handsontable const updates = (state = initialReduxStoreState, action) => { switch (action.type) { case 'updateData': const newData = state.data.slice(0); for (let [row, column, oldValue, newValue] of action.dataChanges) { newData[row][column] = newValue; } return Object.assign({}, state, { data: newData }); case 'updateReadOnly': return Object.assign({}, state, { readOnly: action.readOnly }); default: return state; } }; const actionReducers = combineReducers({updates}); const reduxStore = createStore(actionReducers); class MyComponent extends React.Component { constructor(props) { super(props); this.toggleReadOnly = this.toggleReadOnly.bind(this); this.hotTableComponent = React.createRef(); reduxStore.subscribe(this.updateReduxPreview); reduxStore.subscribe(render); } get reduxHotSettings() { return reduxStore.getState().updates; } componentDidMount() { this.updateReduxPreview(); } onBeforeHotChange(changes, source) { reduxStore.dispatch({ type: 'updateData', dataChanges: changes }); return false; } toggleReadOnly(event) { reduxStore.dispatch({ type: 'updateReadOnly', readOnly: event.target.checked }); } updateReduxPreview() { // This method serves only as a renderer for the Redux's state dump. const previewTable = document.querySelector('#redux-preview table'); const currentState = reduxStore.getState().updates; let newInnerHtml = ''; for (const [key, value] of Object.entries(currentState)) { newInnerHtml += ``; if (key === 'data' && Array.isArray(value)) { newInnerHtml += `data:
`; for (let row of value) { newInnerHtml += ``; for (let cell of row) { newInnerHtml += ``; } newInnerHtml += ``; } newInnerHtml += `
${cell}
`; } else { newInnerHtml += `${key}: ${value}`; } newInnerHtml += ``; } newInnerHtml += ``; previewTable.innerHTML = newInnerHtml; } render() { return (

Redux store dump:

); } } const render = () => { ReactDOM.render(, document.getElementById('example1')); }; render();

Edit this page