通过redux使用HTML <form>的过程如下:
npm install redux react-redux
import { createStore } from 'redux';
const initialState = {
formData: {}
};
function formReducer(state = initialState, action) {
switch (action.type) {
case 'UPDATE_FORM_DATA':
return {
...state,
formData: {
...state.formData,
[action.payload.name]: action.payload.value
}
};
default:
return state;
}
}
const store = createStore(formReducer);
import React from 'react';
import { Provider } from 'react-redux';
import { store } from './store';
import FormComponent from './FormComponent';
function App() {
return (
<Provider store={store}>
<FormComponent />
</Provider>
);
}
export default App;
import React from 'react';
import { connect } from 'react-redux';
function FormComponent({ formData, updateFormData }) {
const handleInputChange = (event) => {
const { name, value } = event.target;
updateFormData(name, value);
};
return (
<form>
<input type="text" name="username" value={formData.username} onChange={handleInputChange} />
<input type="password" name="password" value={formData.password} onChange={handleInputChange} />
</form>
);
}
const mapStateToProps = (state) => ({
formData: state.formData
});
const mapDispatchToProps = (dispatch) => ({
updateFormData: (name, value) => dispatch({ type: 'UPDATE_FORM_DATA', payload: { name, value } })
});
export default connect(mapStateToProps, mapDispatchToProps)(FormComponent);
在上述代码中,handleInputChange函数用于处理表单输入框的变化,并通过updateFormData函数将输入框的name和value传递给Redux store。
这样,通过redux使用HTML <form>的过程就完成了。你可以在Redux store中存储表单数据,并通过dispatch方法更新表单数据的action来实现表单的状态管理。
领取专属 10元无门槛券
手把手带您无忧上云