通过在React中使用useRef钩子获取另一个组件的宽度来调整一个组件的大小

问题描述 投票:1回答:1

我试图通过在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);
javascript reactjs
1个回答
2
投票

btn即将成为引发麻烦的nullref也会选择你在组件级定义的风格。如果我理解正确,那么在第一个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 />
    </>
  )
}

工作实例 - https://codepen.io/swapnesh/pen/ywPRWG

© www.soinside.com 2019 - 2024. All rights reserved.