问题
I have a component with a div.modal
that I would like to transition with CSS. The initial values are set for w=0 and h=0, transition is all, 1s.
This component is a conditional render wihin another component named - <Starter />
, which in turn is a component of <Home />
.
I have tried this in a number of places however the DOM is not ready
{ document.getElementsByClassName('modal').style.width = 'auto' }
The component:
const JoinSign = () => {
return (
<div id="overlay">
<div className="modal">
<h2>Join Sign in</h2>
</div>
</div>
);
}
export default JoinSign;
回答1:
The simplest approach for me is just to add a class to modal and do a useEffect:
const JoinSign = () => {
const [additionalClass, setAdditionalClass] = useState('')
useEffect(() => {
setTimeout(() => { //not sure it is required but
setAdditionalClass('open')
}, 1);
return () => setAdditionalClass('') //clean up function
}, [])
return (
<div id="overlay">
<div className={`modal ${additionalClass}`}>
<h2>Join Sign in</h2>
</div>
</div>
);
}
export default JoinSign
And you handle the animation with just plain css on .modal.open
回答2:
You can just add width
property to a component dynamically
const JoinSign = () => {
const [width, setWidth] = useState(20);
return (
<div id="overlay">
<div className="modal" style={{width: width}}>
<h2>Join Sign in</h2>
</div>
</div>
);
}
export default JoinSign;
and then change width using
setWidth(50);
or when the component mounts
const JoinSign = () => {
const [width, setWidth] = useState(20);
useEffect(() => {
setWidth(50);
});
return (
<div id="overlay">
<div className="modal" style={{width: width}}>
<h2>Join Sign in</h2>
</div>
</div>
);
}
export default JoinSign;
来源:https://stackoverflow.com/questions/65979626/javascript-in-react-to-modify-the-dom