React input 或 material-ui TextField 在 material-ui TreeView 中不起作用

IT技术 reactjs input treeview material-ui
2021-05-12 15:57:51

遇到一种奇怪的情况,即当放入 material-ui TreeView 时,无论是 react input 还是 material-ui TextField 都不起作用。拉出 TreeView 时同样的工作。分享下面的代码

自定义树视图.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;

索引.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);

编辑敏锐草-l79uc

1个回答

TreeView支持各种键盘导航功能,例如在节点之间移动的箭头键,以及移动到包含以键入的字符开头的文本的节点的文本字符。在 中TreeItem,使用该onKeyDown事件,并在处理可能导航的字符后,调用 event.preventDefault()这可以防止事件具有在输入字段中键入的默认效果。

您可以TreeItem通过添加onKeyDown={e => e.stopPropagation()}到您的输入来防止 keyDown 事件传播到当焦点位于您的输入上来解决此问题,如下所示。

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>
    </>
  );
};

在 TreeView 中编辑输入

同样的方法也适用于TextField