[英]Setting the value of a MUI file TextField causes an exception
I"m trying to set the value of a MUI Textfield that has type="file"
props,我正在尝试设置具有
type="file"
道具的 MUI 文本字段的值,
and this exception appears in the console:并且此异常出现在控制台中:
Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable
Only an empty string doesn't causing this exception.只有空字符串不会导致此异常。
Here is my component:这是我的组件:
const MyComponent = () => {
const [image, setImage] = useState("");
const handleImageChange = (event) => {
event.preventDefault();
let reader = new FileReader();
let file = event.target.files[0];
reader.onloadend = () => {
setImage(reader.result);
};
reader.readAsDataURL(file);
};
return (
<TextField
helperText="Cover photo"
type="file"
value={image}
onChange={handleImageChange}
/>
);
};
I tried to simplify the component (still same exception):我试图简化组件(仍然是相同的异常):
<TextField type="file" value={"https://www.someSite.com/image.jpg"} />
Also, I tried to set the value of the input itself using InputProps
, still the same exception.另外,我尝试使用
InputProps
设置输入本身的值,仍然是相同的异常。
According to MUI Docs value
could be 'any' regardless the type
:根据 MUI Docs,无论
type
如何, value
都可以是“任何”:
One solution for your problem would be this:您的问题的一种解决方案是:
You are trying to set a string in an input file, I will explain next steps to solve this您正在尝试在输入文件中设置一个字符串,我将解释解决此问题的后续步骤
ref
ref
InputProps
from your main TextField
TextField
在InputProps
中添加一个图标onClick
to this icon to call refs input to pop up to choose fileonClick
调用refs输入弹出选择文件onChange
to input file to call your previous method created (handleImageChange)onChange
添加到输入文件以调用您之前创建的方法 (handleImageChange)image
string to main TextField
image
字符串分配给主TextField
This is an example code that works:这是一个有效的示例代码:
export default function App() {
const inputFileRef = useRef(null)
const [image, setImage] = useState("")
const handleClickInputFile = () => {
inputFileRef.current.click()
}
const handleChangeInputFile = (event) => {
event.preventDefault();
let reader = new FileReader();
let file = event.target.files[0];
reader.onloadend = () => {
setImage(reader.result);
};
reader.readAsDataURL(file);
}
return (
<div className="App">
<TextField value={image} onChange={(event => setImage(event.target.value))} multiline fullWidth InputProps={{
endAdornment: <InputAdornment position="start" onClick={handleClickInputFile} style={{cursor:"pointer"}}>Click</InputAdornment>,
}}/>
<input type="file" ref={inputFileRef} onChange={handleChangeInputFile} style={{display:"none"}}/>
</div>
);
}
Now you can change the click
text by an icon from mui and that's it!现在您可以通过 mui 中的图标更改
click
文本,仅此而已!
You can check this codesandbox to see the final solution works您可以检查此代码框以查看最终解决方案是否有效
Let me know if you have any problem如果您有任何问题,请告诉我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.