将箭头功能更改为组件列表

时间:2019-07-02 06:42:47

标签: reactjs

我想制作带有标签的div并勾勒出轮廓,并找到了this的答案,这正是我所需要的。但是,当我尝试在OutlinedDiv内使用某些输入时会出现问题。键入任何字符后,它将失去焦点。我发现问题是OutlinedDiv中使用的箭头功能:

inputComponent: ({ className }) => (
      <div key="divKey" className={className}>{children}</div>)

,如果我使用简单的div而不是OutlinedDiv,则一切正常。因此,我可以用可以与输入配合使用的方式重写OutlinedDiv吗?我什至没有感觉我在这里有什么选择。

Edit Custom Outlined Component

index.js

import React from "react";
import ReactDOM from "react-dom";

import OutlinedDiv from "./OutlinedDiv";
import TextField from "@material-ui/core/TextField";

function App() {
  const [state, setState] = React.useState({ inputValue: "", inputValue2: "" });

  function handleChange(event) {
    setState({ ...state, [event.target.name]: event.target.value });
  }

  return (
    <div className="App">
      <OutlinedDiv key="outlinedDivKey" label="OutlinedDivTest">
        <div>
          <TextField
            id="inputValue"
            key="inputValueKey"
            name="inputValue"
            label="Some input"
            inputProps={{ style: { textAlign: "right" } }}
            value={state.inputValue}
            onChange={event => handleChange(event)}
          />
        </div>
        <div>
          <TextField
            id="inputValue2"
            key="inputValueKey2"
            name="inputValue2"
            label="Some input2"
            inputProps={{ style: { textAlign: "right" } }}
            value={state.inputValue2}
            onChange={event => handleChange(event)}
          />
        </div>
      </OutlinedDiv>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

outlinedDiv.js

import React from "react";

import TextField from "@material-ui/core/TextField";

const OutlinedDiv = ({ children, label }) => {
  return (
    <TextField
      variant="outlined"
      label={label}
      multiline
      InputLabelProps={{ shrink: true }}
      InputProps={{
        inputComponent: ({ className }) => (
          <div key="divKey" className={className}>
            {children}
          </div>
        )
      }}
    />
  );
};
export default OutlinedDiv;

1 个答案:

答案 0 :(得分:1)

我已经更新了之前的答案,将以下内容用于OutlinedDiv实现:

import React from "react";

import TextField from "@material-ui/core/TextField";

const InputComponent = ({ inputRef, ...other }) => <div {...other} />;
const OutlinedDiv = ({ children, label }) => {
  return (
    <TextField
      variant="outlined"
      label={label}
      multiline
      InputLabelProps={{ shrink: true }}
      InputProps={{
        inputComponent: InputComponent
      }}
      inputProps={{ children: children }}
    />
  );
};
export default OutlinedDiv;

这样可以避免在重新渲染时重新安装输入组件。

这是您的沙盒的修改版本:

https://codesandbox.io/s/custom-outlined-component-sv2bi