我在我的React项目中使用Material UI,但是我想获得一个Dialog的高度。所以,我试图做这样的事情:
import Dialog from '@material-ui/core/Dialog';
class MyDialog extends React.Component {
constructor(props) {
super(props);
this.dialogRef = React.createRef();
}
render() {
if (this.dialogRef.curent) {
console.log(this.dialogRef.current);
}
return (
<Dialog maxWidth='sm'
innerRef={this.dialogRef}
>
// Rest removed for brevity
</Dialog>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(withLocalize(MyDialog)));
现在使用上面的代码,我看到一个用console.log(this.dialogRef)
行打印的对象,它具有名为refs
的属性,它是一个空对象。在这种情况下,如何获得Dialog
的高度?是在MyDialog
组件内部,还是假设我有另一个名为Main
的组件,它在其render方法中调用了MyDialog
?
请注意,我正在使用"react": "^16.6.3"
和"@material-ui/core": "^3.6.1"
。
答案 0 :(得分:1)
自Material-UI v4.0.0-alpha.3。起,您可以直接使用ref
道具。
function MyComponent() {
const myRef = React.useRef();
return <Dialog ref={myRef} />;
}
答案 1 :(得分:1)
我相信RootRef在这种情况下会找到错误的DOM元素。我想您希望对话框中Paper组件中的div获得高度。您可以通过覆盖Paper的组件来做到这一点:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/local/bin/npm', 'install', 'hooper' ]
2 info using npm@6.9.0
3 info using node@v8.10.0
4 verbose config Skipping project config: /home/juanlh/.npmrc. (matches userconfig)
5 verbose npm-session e3d2c58aee19e2f6
6 silly install loadCurrentTree
7 silly install readLocalPackageData
8 timing stage:rollbackFailedOptional Completed in 6ms
9 timing stage:runTopLevelLifecycles Completed in 124ms
10 verbose stack Error: Failed to parse json
10 verbose stack Unexpected end of JSON input while parsing near ''
10 verbose stack at parseError (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:452:11)
10 verbose stack at parseJson (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:104:26)
10 verbose stack at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:51:5
10 verbose stack at /usr/local/lib/node_modules/npm/node_modules/graceful-fs/graceful-fs.js:90:16
10 verbose stack at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)
11 verbose cwd /home/juanlh
12 verbose Linux 4.18.0-16-generic
13 verbose argv "/usr/bin/node" "/usr/local/bin/npm" "install" "hooper"
14 verbose node v8.10.0
15 verbose npm v6.9.0
16 error file /home/juanlh/package.json
17 error code EJSONPARSE
18 error JSON.parse Failed to parse json
18 error JSON.parse Unexpected end of JSON input while parsing near ''
19 error JSON.parse Failed to parse package.json data.
19 error JSON.parse package.json must be actual JSON, not just JavaScript.
20 verbose exit [ 1, true ]
const PaperComponent = ({ dialogRef, ...other }) => {
return <div ref={dialogRef} {...other} />;
};
这是您的沙盒的修改版本:https://codesandbox.io/s/2vxz5lq1jr