JavaScript in React to modify the DOM

做~自己de王妃 提交于 2021-02-11 06:54:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!