簡體   English   中英

用特定的className反應元素的set min-height屬性

[英]React set min-height property of element with specific className

我有一個React組件,在componentDidMount()' I want to set the className =“ content-wrapper”`設置為'600px' property of an element where componentDidMount()' I want to set the min-height property of an element where

我嘗試了以下方法:

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

不幸的是,這導致以下錯誤:

未捕獲的TypeError:無法設置未定義的屬性'minHeight'

在MyComponent.componentDidMount

我仍然對React持保留態度,並希望能為實現該目標提供任何幫助。 謝謝!

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

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

您尚未發布如何創建內容包裝器。

如果您執行以下操作:

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

然后修改DOM直接違背了React(即使可能可行),因為React使用虛擬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}} />
 }
}

如果僅對1 div進行編碼,則可以硬編碼600px,或者可以將一個類動態添加到content-wrapper中,並將CSS中的minHeight設置為600px。

如果您要在多個組件中更改多個content-wrapper div,則需要將狀態提升到更高的組件,並將其作為道具傳遞,或者如果它們完全無關,請使用Redux或Flux。

您也可以直接使用ReactDOM操作DOM節點。 使用TypeScript(當然也適用於JS):

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

此功能可以在被稱為componentDidMount()並且,如果你想在每次組件重新渲染時間更新最小高度,在componentDidUpdate()為好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM