【发布时间】:2021-05-09 03:21:00
【问题描述】:
在我的 Datatable 中,当我在输入中键入任何字符并在组件内定义组件时,输入会失去焦点。但是,当我将组件直接放在数据表中时,它可以工作。我知道第一种情况不起作用,因为每次我输入一个字符时组件都会重新呈现。但为什么第二种情况有效?以及如何在不将代码直接放在数据表中的情况下使第一个案例工作。
代码沙盒:https://codesandbox.io/s/test-2p30w
不工作(第一种情况)
import Datatable from "react-table";
import { useState } from "react";
const Test = () => {
const [first, setFirst] = useState("");
const [second, setSecond] = useState("");
const Field1 = () => (
<input
defaultValue={first}
onChange={(e) => setFirst(e.currentTarget.value)}
/>
);
const Field2 = () => (
<input
defaultValue={second}
onChange={(e) => setSecond(e.currentTarget.value)}
/>
);
return (
<Datatable
noText
pageSize={1}
showPagination={false}
data={[{ userName: "asdas", email: "asdsad" }]}
columns={[
{
Header: "www",
accessor: "userName",
Cell: <Field1 />
},
{
Header: "Email",
accessor: "email",
Cell: <Field2 />
}
]}
/>
);
};
export default Test;
工作(第二种情况)
import Datatable from "react-table";
import { useState } from "react";
const Test = () => {
const [first, setFirst] = useState("");
const [second, setSecond] = useState("");
return (
<Datatable
noText
pageSize={1}
showPagination={false}
data={[{ userName: "asdas", email: "asdsad" }]}
columns={[
{
Header: "www",
accessor: "userName",
Cell: (
<input
defaultValue={first}
onChange={(e) => setFirst(e.currentTarget.value)}
/>
)
},
{
Header: "Email",
accessor: "email",
Cell: (
<input
defaultValue={second}
onChange={(e) => setSecond(e.currentTarget.value)}
/>
)
}
]}
/>
);
};
export default Test;
【问题讨论】:
标签: javascript reactjs react-table