#reactjs
Вопрос:
Я использую пользовательский интерфейс Material и хочу создать свой собственный Field
, который является базовым компонентом и Text
используется Field
для ввода формы.
Вот мой Field
код:
import React, { useState, useEffect, useRef, useContext } from "react";
import FormControl from "@material-ui/core/FormControl";
import FormHelperText from "@material-ui/core/FormHelperText";
import InputLabel from "@material-ui/core/InputLabel";
const Field = ({
column,
placeholder,
children,
type,
value,
hint,
validationStateProvider
}) => {
const [id, setId] = useState();
const [helpTextId, setHelpTextId] = useState();
const [currentValue, setCurrentValue] = useState(value || "");
const [helpText, setHelpText] = useState(hint);
const initialHint = hint;
const [validationState, setValidationState] = useState(null);
useEffect(() => {
setId(`${type}_${column}`);
}, [column]);
useEffect(() => {
setHelpTextId(`${id}_help`);
}, [id]);
useEffect(() => {
validationStateProvider(currentValue);
}, [currentValue]);
const isValid = () => {
if (!validationState) {
return false;
}
if (validationState.indexOf("invalid") > -1) {
return false;
}
return true;
};
useEffect(() => {
// emit an event
}, [validationState]);
return (
<div className="field">
<FormControl error={isValid() ? false : true} fullWidth>
<InputLabel htmlFor={id}>{placeholder}</InputLabel>
{React.cloneElement(children, {
id: id,
value: currentValue,
"aria-describedby": helpTextId,
handleChange: (e) => {
setCurrentValue(e.target.value);
}
})}
{/* {children(currentValue, setCurrentValue)} */}
<FormHelperText id={helpTextId}>{helpText}</FormHelperText>
</FormControl>
</div>
);
};
Field.muiName = "Field";
export { Field };
И вот мой Text
код:
import Input from "@material-ui/core/Input";
import { useState, useEffect, useRef, useContext } from "react";
import { Field } from "./Field";
const Text = ({ column, required, placeholder, hint, value, handleChange }) => {
const htmlInput = useRef();
const getValidationState = (currentValue) => {
if (required amp;amp; currentValue) {
return "invalid required";
}
return "valid";
};
return (
<Field
type="text"
validationStateProvider={getValidationState}
column={column}
placeholder={placeholder}
hint={hint}
value={value}
>
{({ value, onChange }) => {
return (
<Input
inputRef={htmlInput}
required={required ? true : false}
onChange={handleChange}
/>
);
}}
{/* <Input
inputRef={htmlInput}
required={required ? true : false}
onChange={handleChange}
/> */}
</Field>
);
};
Text.muiName = Field.muiName;
export { Text };
Вы можете увидеть код и поле.
Как я могу это решить?