简体   繁体   中英

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.

Is there a way to get and pass this property?

I keep getting "TypeError: Cannot read property 'refs' of undefined"

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:

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. DOM element references allow you to access most properties of the particular DOM element referenced.

You haven't bound "this". Try height={() => this.refs.container.height}

If your Services component is inside lets say ServicesWrapper Component, what you should do is put on it

`servicesWrapperContainerRef = React.createRef()`;

Then, on JSX of wrapper component place

`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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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