我有一个React组件位于componentDidMount()' I want to set the
min-height property of an element where
className =" content-wrapper"`to' 600px'。
我尝试了以下内容:
componentDidMount() {
document.getElementsByClassName('content-wrapper').style.minHeight = "600px"
}
不幸的是,会导致以下错误:
未捕获的TypeError:无法设置属性' minHeight'未定义的
at MyComponent.componentDidMount
我仍然掌握了React,并希望在实现这一目标方面有任何帮助。谢谢!
答案 0 :(得分:1)
获取元素,迭代并设置样式。
componentDidMount() {
document.querySelectorAll('.content-wrapper').forEach(el => el.style.minHeight = '600px');
}
答案 1 :(得分:1)
您还没有发布如何创建内容包装器。
如果你做了这样的事情:
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。
如果您想要在多个组件中更改多个内容包装器div,则需要lift the state up更高的组件并将其作为道具传递或使用Redux或Flux(如果它们完全不相关)。
答案 2 :(得分:0)
您也可以使用ReactDOM直接操作DOM节点。使用TypeScript(当然也适用于JS):
private setMinHeight = () => {
const thisNode = ReactDOM.findDOMNode(this) as HTMLElement;
if (thisNode) {
thisNode.style.minHeight = (...);
}
}
可以在componentDidMount()
中调用此函数,如果您希望每次重新渲染组件时更新最小高度,也可以在componentDidUpdate()
中调用。