我试图通过在React中使用useRef钩子来设置组件的宽度,但我显然不是在研究模式。代码框可以在这里找到:https://codesandbox.io/s/vqn5jyv9y5。谢谢!
import React, {useRef} from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Foo />
</div>
);
}
const Foo = () => {
const { current: btn } = useRef(null);
return (
<React.Fragment>
<button ref={btn}>buuuuttttoooon</button>
<div style={{ width: btn.style.width, backgroundColor: 'pink', height: '50px' }} />
</React.Fragment>
)
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
btn
即将成为引发麻烦的null
,ref
也会选择你在组件级定义的风格。如果我理解正确,那么在第一个HTML元素的基础上,您想要修改另一个HTML元素的样式。
请找到我使用state
修改的代码 -
const Foo = () => {
const [count, setCount] = React.useState('100px')
const refElem = React.useRef(0)
return (
<>
<button
ref={refElem => {
if(refElem) {
setCount(refElem.style.width)
}
}
}
style={{
width: '700px'
}}>This is a button 1</button>
<hr />
<button style={{width: count}}>This is a button 2 = {count}</button>
<hr />
</>
)
}