问题
Stuck with a strange situation where neither react input nor material-ui TextField works when put inside a material-ui TreeView. The same work when pulled out of the TreeView. Sharing the code below
CustomTreeView.js
import React, { useState } from "react";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";
import TreeView from "@material-ui/lab/TreeView";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import TreeItem from "@material-ui/lab/TreeItem";
const MyInput = () => {
const inputState = useState("");
const [value, setValue] = inputState;
return (
<>
<input
placeholder="Type here…"
value={value}
onChange={e => setValue(e.currentTarget.value)}
/>
<button onClick={() => setValue("")}>Reset</button>
<p>Current value: {value || "N/A"}</p>
</>
);
};
const CustomTreeView = () => (
<>
<TreeView
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
>
<TreeItem nodeId="1" label="TreeView">
<Grid
container
direction="row"
justify="flex-start"
alignItems="center"
spacing={1}
>
<Grid
container
direction="row"
justify="flex-start"
alignItems="center"
item
xs={12}
>
<Paper>
<MyInput />
</Paper>
</Grid>
</Grid>
</TreeItem>
</TreeView>
</>
);
export default CustomTreeView;
index.js
import React from "react";
import ReactDOM from "react-dom";
import CustomTreeView from "./treeView";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<CustomTreeView />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
回答1:
TreeView
supports various keyboard navigation features such as arrow keys moving between nodes and also text characters moving to nodes that contain text starting with the characters typed. In TreeItem
, the onKeyDown
event is used and, after processing characters for possible navigation, it calls event.preventDefault(). This prevents the event from having its default effect of typing in your input field.
You can fix this, by preventing keyDown events from propagating to the TreeItem
when focus is on your input by adding onKeyDown={e => e.stopPropagation()}
to your input as shown below.
const MyInput = () => {
const inputState = useState("");
const [value, setValue] = inputState;
return (
<>
<input
onKeyDown={e => e.stopPropagation()}
placeholder="Type here…"
value={value}
onChange={e => setValue(e.currentTarget.value)}
/>
<button onClick={() => setValue("")}>Reset</button>
<p>Current value: {value || "N/A"}</p>
</>
);
};
The same approach also works for TextField.
来源:https://stackoverflow.com/questions/59063602/react-input-or-material-ui-textfield-not-working-inside-material-ui-treeview