简体   繁体   中英

React set min-height property of element with specific className

I have a React Component where on componentDidMount()' I want to set the min-height property of an element where className="content-wrapper"` to '600px'.

I have tried the following:

componentDidMount() {
    document.getElementsByClassName('content-wrapper').style.minHeight = "600px"
}

Unfortunately that results in the following error:

Uncaught TypeError: Cannot set property 'minHeight' of undefined

at MyComponent.componentDidMount

I'm still getting the hang of React and would appreciate any help possible in achieving this goal. Thanks!

Get elements, iterate and set style.

componentDidMount() {
    document.querySelectorAll('.content-wrapper').forEach(el => el.style.minHeight = '600px');
}

You haven't posted how you created content-wrapper still.

If you did something like this:

class Component extends React.Component {
    render() {
        return <div className="content-wrapper"/>
    }
}

Then modifying the DOM directly goes against React (even though it may work) because React uses a virtual DOM to see what has changed since last render. Therefore if you modify the DOM directly, React will overwrite these changes because it's looking at the previous virtual DOM and thinks nothing changed.

Instead you will want:

class Component extends React.Component {
   componentDidMount() {
       this.setState({conentWrapperMinHeight: "600px"})
   }
   render() {
       return <div className="content-wrapper" style={{minHeight: this.state.conentWrapperMinHeight}} />
 }
}

You could just hardcode 600px in if you do it for 1 div only or you could dynamically add a class to content-wrapper and set minHeight in css to 600px.

If you have multi content-wrapper div's that you want to change in multiple components then you will need to lift the state up to a higher component and pass it down as props or use Redux or Flux if they are completely unrelated.

You may also manipulate the DOM node directly using ReactDOM. Using TypeScript (but applicable to JS as well of course):

private setMinHeight = () => {
    const thisNode = ReactDOM.findDOMNode(this) as HTMLElement;
    if (thisNode) {
        thisNode.style.minHeight = (...);
    }
}

This function may be called in componentDidMount() , and, if you want it to update min-height every time the component is re-rendered, in componentDidUpdate() as well.

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