2016-12-25 189 views
0

我有一個React組件,其中componentDidMount()' I want to set the最小高度爲property of an element where className =「content-wrapper」爲「600px」。React設置具有特定className的元素的min-height屬性

我曾嘗試以下:

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

不幸的結果在下面的錯誤:

Uncaught TypeError: Cannot set property 'minHeight' of undefined

at MyComponent.componentDidMount

我仍然得到陣營的竅門,並希望得到任何幫助可能實現這一目標。謝謝!

+0

content-wrapper是你在一個反應​​組件中創建的元素還是僅僅使用標準的html或js? –

+0

這只是一個'div'標籤 –

+0

好吧,如果你在反應組件中創建了這個'div'標籤,那麼它將是一個虛擬的'div'。在這種情況下,接受的答案不是你想要的,因爲你直接修改了不好的DOM。如果它是一個正常的html文件中的div或使用普通的JS創建的,那麼它就沒有問題。 –

回答

1

您還未發佈如何創建content-wrapper。

如果你做了這樣的事情:

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

然後修改DOM直接違背陣營(儘管它可能工作),因爲陣營使用虛擬DOM,看看發生了什麼變化自去年呈現。因此,如果您直接修改DOM,則React將覆蓋這些更改,因爲它正在查看以前的虛擬DOM並認爲沒有任何更改。

相反,你會想:

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

你可以只硬編碼在600px的,如果你只是做了1個格或你可以動態地在CSS類添加到內容的包裝,並設置到了minHeight 600px的。

如果您有多個內容包裝div,您想要在多個組件中進行更改,那麼您需要lift the state up作爲更高的組件,並將其作爲道具傳遞,或者如果它們完全不相關,則使用Redux或Flux。

+0

我只有一個內容包裝'div',所以很好,但謝謝。如果你說的是真的,這是更好的做法,那麼我感謝你的回答和努力。 –

+0

@BarryMichaelDoyle即使它只是一個div,如果它是一個**虛擬** div,那麼你想硬編碼的值像'style = {{minHeight:「600px」}}'而不是通過DOM –

+0

是的,這也有幫助有很多我的後續問題.. –

1

獲取元素,迭代和設置樣式。

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

完美的作品!謝謝:) –