import React, { useRef } from 'react';
function MyComponent() {
const divRef = useRef(null);
const handleClick = () => {
divRef.current.style.setProperty('background-color', 'red');
};
return (
<div ref={divRef} onClick={handleClick}>
Click me to change my background color!
</div>
);
}
handleClick 함수를 들여다보면 setProperty() 메서드를 통하여 div의 background-color 스타일 속성을 red로 변경하고 있다.
import React, { useRef } from 'react';
function MyComponent() {
const boxRef = useRef(null);
const handleButtonClick = () => {
boxRef.current.style.setProperty('transform', 'translateX(100px)');
};
return (
<div>
<div
ref={boxRef}
style={{ width: '50px', height: '50px', backgroundColor: 'red' }}
></div>
<button onClick={handleButtonClick}>Move Right</button>
</div>
);
}