简体   繁体   English

如何在reactjs中获取元素属性

[英]How to get element properties in reactjs

I'm trying to get the height of the parent container element, to use as a height of an SVG background element.我正在尝试获取父容器元素的高度,以用作 SVG 背景元素的高度。

Is there a way to get and pass this property?有没有办法获得和传递这个属性?

I keep getting "TypeError: Cannot read property 'refs' of undefined"我不断收到“TypeError:无法读取未定义的属性‘refs’”

const Services = ({ classes }) => {
    return (
        <div className={classes.Container} ref="container">//Element I want the height of
            <div className={classes.BGContainer}>
                <BGSVG width={'210'} height={this.refs.container.height} color={'blue'} />//Where I want to pass height to
            </div>
            <div className={classes.Services}>
                {services.map((e, i) => (
                    <ServiceItem
                        title={e.title}
                        icon={e.icon}
                        info={e.info}
                        inverted={i % 2 === 1 ? true : false}
                    />
                ))}
            </div>
        </div>
    );

In a functional component, you need to use the React Hook called useRef like this:在函数式组件中,您需要像这样使用名为useRef的 React Hook:

const TextInputWithFocusButton = (props) => {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

you will see if you log out inputEl that a reference to the input element is logged.如果您注销inputEl ,您将看到是否记录了对输入元素的引用。 DOM element references allow you to access most properties of the particular DOM element referenced. DOM 元素引用允许您访问所引用的特定 DOM 元素的大多数属性。

You haven't bound "this".你还没有绑定“这个”。 Try height={() => this.refs.container.height}试试 height={() => this.refs.container.height}

If your Services component is inside lets say ServicesWrapper Component, what you should do is put on it如果你的服务组件在里面让我们说 ServicesWrapper 组件,你应该做的是把它放在上面

`servicesWrapperContainerRef = React.createRef()`;

Then, on JSX of wrapper component place然后,在wrapper组件的JSX上

`ref={this.servicesWrapperContainerRef}`

and then, pass that as a prop to the Services component like this const Services = ({ classes, servicesWrapperContainerRef }) and then you can use it to find out the parents height然后,将它作为道具传递给 Services 组件,就像这样 const Services = ({ classes, servicesWrapperContainerRef }) 然后你可以用它来找出父母的高度

`height={this.props.servicesWrapperContainerRef.current.clientHeight}`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM