如何更改 Material UI 文本字段组件的光标起始位置?我们正在使用最新版本的材料 UI,并且我们在我的项目中使用测试字段组件,但光标指示位置不在正确的位置。那么,我们如何改变光标的起始位置。
我们尝试这3种方法
第一
<TextField
// ... other props
sx={{
"& input": {
padding: "10px",
},
}}
/>
第二个
<TextField
label="Username"
placeholder="Enter your username"
inputProps={{ selectionStart: 5 }} // Set the starting cursor position
/>
第三,我们使用 useRef 来实现这一点,但这也不起作用
import React, { useState, useEffect, useRef } from "react";
import TextField from "@mui/material/TextField";
export default function CustomizedTextField() {
const [startCursorPosition, setStartCursorPosition] = useState(5);
const inputRef = useRef(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
inputRef.current.setSelectionRange(startCursorPosition, startCursorPosition);
}
}, [startCursorPosition]);
return (
<TextField
label="Username"
placeholder="Enter your username"
inputRef={inputRef}
onFocus={() => setStartCursorPosition(5)} // Set the desired starting position
/>
);
}
您可以使用
inputProps
属性访问 TextField 组件的 html 输入字段属性。
<TextField
inputProps={{
style: {
paddingLeft: "50px"
}
}}
/>