我想在表头上添加列筛选器,但在每次输入后,它会失去焦点。
我的主要组件:searchColArr
是一个本地状态,而 fetchData
中使用的所有其他状态都是 redux 状态,它们使用 useSelector
进行初始化。
Category.jsx
const [searchColArr, setSearchColArr] = useState({
name: "",
});
//all these default value are either local state or redux state
function fetchData(
newPage = page,
newPerPage = perPage,
newOrder = order,
newDir = dir,
newSearchColArr = searchColArr,
newSearch = search
) {
dispatch(
listCategory(
newPage,
newPerPage,
newOrder,
newDir,
newSearchColArr,
newSearch
)
);
}
const headerRow = React.useMemo(
() => [
{
header: "Name",
name: "name",
filter: true,
sort: true,
},
{
header: "Action",
name: "id",
filter: false,
sort: false,
},
],
[]
);
const TBody = () => {
return (
<tbody key="tbody">
{list &&
list.map((row, i) => (
<tr key={row.id}>
<td>{row.name}</td>
<td>
<ActionColumn id={row.id} />
</td>
</tr>
))}
</tbody>
);
};
const handleColSearch = ({ currentTarget: input }) => {
setSearchColArr({
...searchColArr,
[input.name]: input.value,
});
};
useEffect(() => {
fetchData();
}, [searchColArr]);
return (
<div className="row">
<div className="col-md-12">
{/* REDUX TABLE STARTS */}
<ReduxTable
key="redux-table"
isLoading={isLoading}
headerRow={headerRow}
list={list}
page={page}
perPage={perPage}
order={order}
dir={dir}
total={total}
totalPage={totalPage}
searchColArr={searchColArr}
handlePageLengthChange={handlePageLengthChange}
handlePageChange={handlePageChange}
handleColSearch={handleColSearch}
TBody={TBody}
/>
{/* REDUX TABLE ENDS */}
</div>
</div>
);
在Redux Table中,我正在加载另一个组件ReduxTableHeader
ReduxTable
const ReduxTable = ({
isLoading,
headerRow,
list,
page,
perPage,
order,
dir,
total,
totalPage,
searchColArr,
handlePageLengthChange,
handlePageChange,
handleColSearch,
TBody,
}) => {
return (
<div className="card-box">
{/* TABLE HEADER AND BODY just looping thorugh list*/}
<table
id="basicTable"
className="table table-bordered action-table table-striped table-hover mb-0"
>
{/* ReduxTableHeader */}
<ReduxTableHeader
key="redux-table-header"
headerRow={headerRow}
searchColArr={searchColArr}
handleColSearch={handleColSearch}
/>
<TBody />
</table>
</div>
);
};
Redux表头
return (
<thead key="thead">
<tr>
//list of header name
</tr>
<tr key="filter-row">
{headerRow &&
headerRow.map((v, i) => (
<th key={v.name}>
{v.filter ? (
<input
type="search"
className="form-control form-control-sm d-inline-block"
placeholder=""
aria-controls="datatable"
name={v.name}
value={searchColArr[v.name] || ""}
onChange={handleColSearch}
autoComplete="off"
key={"index" + i}
/>
) : (
""
)}
</th>
))}
</tr>
</thead>
);
我正在加载一个输入字段的表头,但每当我在这个字母上打字时,它就会失去自动聚焦。我该如何修复它?
handleColSearch
后都会重新渲染。如果没有更多上下文,将很难进一步诊断。 - Dave Newton