我想知道是否有一种方法可以使用如下语法向react组件添加样式和属性。
const rect = <rect></rect>
rect.style.fill = "black"
rect.style.height = "50px"
rect.style.width = "50px"
这不起作用(或者我不会问(,但有类似的东西吗?
谢谢!
使用refs是可能的。
const { useEffect, useRef } = React;
const App = () => {
const ref = useRef(null);
const rect = <div ref={ref}></div>;
useEffect(() => {
ref.current.style.background = "black";
ref.current.style.height = "50px";
ref.current.style.width = "50px";
}, []);
return rect;
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>