问题
The moment i wrap "form" element with Material UI "Dialog", I get an "Cannot read property 'offsetWidth' of null" error, which makes it impossible for automatic width of InputLabel to work.
When i remove Dialog it works just fine and InputLabelRef is properly read on ComponentDidmount.
sandbox with example: https://codesandbox.io/s/1q98z07w13
I need it to be wrapped with Dialog. What might be the issue here?
回答1:
The reason that this is occurring is because the components inside of your dialog are not rendered when componentDidMount
is called, even if your default state is open === true
.
The trick here is to make sure that your form will always be mounted when componentDidMount
is called. To do this you need to split your form out into a seperate component altogether that sits inside of your Dialog
component. This way componentDidMount
is called when the Dialog
displays your seperate component and not when the Dialog
itself has rendered.
I've updated your sandbox to include the changes I've mentioned: https://codesandbox.io/s/zw705046w3
回答2:
For anyone else who wants to still use the outlined select without needing it to be rendered on mount, you can just use Material UI's TextField component but pass it the select
prop and label (as you normally would with other text fields). The offSetWidth label property is handled for you.
Here's a working sandbox showing select but with the TextField wrapper.
Although I don't show it, you can take my word for it that if you render this post-mount it will not complain with any errors.
来源:https://stackoverflow.com/questions/53547043/cannot-read-property-offsetwidth-of-null-when-using-material-ui-dialog