通过自定义组件格式化ref



我有这个代码

import MuiDialog from "@mui/material/Dialog";
import { styled } from "@mui/material/styles";
const TheDialog = styled((DialogProps) => (
<MuiDialog  {...DialogProps} />
))(({ theme }) => ({
"& .css-tlc64q-MuiPaper-root-MuiDialog-paper": {

background: "linear-gradient(90deg, rgb(142, 31, 195) 0%, rgb(6, 111, 197) 100%)",
color:"white"
},
"& .css-tlc64q-MuiPaper-root-MuiDialog-paper *": {

color:"white"
},
"& .css-tlc64q-MuiPaper-root-MuiDialog-paper button *": {


color:"black"
},
"& .css-tlc64q-MuiPaper-root-MuiDialog-paper button": {


alignItems: "center",
background: "#FFFFFF",
border: "1px solid rgba(0, 0, 0, 0.1)",
borderRadius: ".25rem",
boxShadow: "rgba(0, 0, 0, 0.02) 0 1px 3px 0",
boxSizing: "border-box",
color: "rgba(0, 0, 0, 0.85)",
cursor: "pointer",
fontFamily: "system-ui,-apple-system,system-ui,Helvetica Neue,Helvetica,Arial,sans-serif",
fontSize: "13px",
fontWeight: "600",
textDecoration: "none",
transition: "all 250ms",
userSelect: "none",
webkitUserSelect: "none",
touchAction: "manipulation",
},
"& .css-tlc64q-MuiPaper-root-MuiDialog-paper button:hover": {


transform: "translateY(-1px)"
},
"& .css-tlc64q-MuiPaper-root-MuiDialog-paper button:focus": {


borderColor: "rgba(0, 0, 0, 0.15)",
boxShadow: "rgba(0, 0, 0, 0.1) 0 4px 12px",
color: "rgba(0, 0, 0, 0.65)"
},
"& .css-tlc64q-MuiPaper-root-MuiDialog-paper button:active": {


backgroundColor: "#F0F0F1",
borderColor: "rgba(0, 0, 0, 0.15)",
boxShadow: "rgba(0, 0, 0, 0.06) 0 2px 4px",
color: "rgba(0, 0, 0, 0.65)",
transform: "translateY(0)"
},


}));
function Dialog({handleClose,open,children}){
return( <TheDialog
onClose={handleClose}
fullWidth={true}
maxWidth={"sm"}
open={open}
>
{children}
</TheDialog>)

}
function App() {
const textAreaRef = React.useRef(null);
const handleClick = () => {
console.log(textAreaRef.current.value);
};
return (
<div className="App">
<Dialog title="My Dialog"
open={true}
handleClose={()=>{}}
title="My Dialog"
>
<textarea ref={textAreaRef} rows="3" placeholder="Enter text here" />
<button onClick={handleClick}>Click me</button>
</Dialog>
</div>
);
}
export default App;

由于某些原因,ref给了我null。

如果我把文本区域放在对话框外面它不会给我空值,像这样:

function App() {
const textAreaRef = React.useRef(null);
const handleClick = () => {
console.log(textAreaRef.current.value);
};
return (
<div className="App">
<textarea ref={textAreaRef} rows="3" placeholder="Enter text here" />
<Dialog
open={true}
handleClose={()=>{}}
title="My Dialog">
<button onClick={handleClick}>Click me</button>
</Dialog>
</div>
);
}

所以我很确定这个错误与传递refs有关,虽然我不知道如何使用它与一个自定义组件有开始和结束标签

我搜索了互联网,甚至试着聊天,找不到答案,所以你是我最后的手段lol

谢谢! !

我用你的代码在Stackblitz上做了一个工作示例。https://stackblitz.com/edit/react-wafgu1?file=src%2FApp.js这似乎有效。

最新更新