rea*_*tor 6 javascript reactjs
我正在尝试通过在 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);
Run Code Online (Sandbox Code Playgroud)
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 />
</>
)
}
Run Code Online (Sandbox Code Playgroud)
工作示例 - https://codepen.io/swapnesh/pen/ywPRWG
归档时间: |
|
查看次数: |
6876 次 |
最近记录: |