解决这个问题的一种方法是使用React的状态管理库,如Redux或Mobx,并结合React的表单组件来实现。
下面是一个示例代码,使用React和Redux来创建一个不重复复制组件的多字段搜索表单:
SearchForm
的组件,它包含多个字段的输入框和一个搜索按钮。import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { search } from './actions';
const SearchForm = () => {
const [field1, setField1] = useState('');
const [field2, setField2] = useState('');
const dispatch = useDispatch();
const handleSubmit = (e) => {
e.preventDefault();
dispatch(search(field1, field2));
};
return (
);
};
export default SearchForm;
search
的action,用于触发搜索操作。// actions.js
export const SEARCH = 'SEARCH';
export const search = (field1, field2) => ({
type: SEARCH,
payload: {
field1,
field2,
},
});
reducer
的reducer函数,用于处理搜索操作。// reducer.js
import { SEARCH } from './actions';
const initialState = {
field1: '',
field2: '',
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case SEARCH:
return {
...state,
field1: action.payload.field1,
field2: action.payload.field2,
};
default:
return state;
}
};
export default reducer;
Provider
组件,并将SearchForm
组件包裹在其中。import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import reducer from './reducer';
import SearchForm from './SearchForm';
const store = createStore(reducer);
const App = () => (
);
export default App;
这样,当用户在搜索表单中输入字段并点击搜索按钮时,SearchForm
组件会触发search
action,更新Redux store中的state。其他使用相同state的组件可以通过订阅store来获取最新的搜索字段值。
上一篇:不重复反斜杠地正确转义所需字符
下一篇:不重复计数查询