【发布时间】:2019-10-02 03:21:46
【问题描述】:
我正在使用 refs 来计算子组件中的块高度,它在内部工作正常,所以在每个 removeHandler() 函数“doCalculating”被调用后
但如果我试图将其调用到父组件中,doCalculating() 总是返回初始值。就像在 componentDidMount() 之后一样 似乎 doCalculating() 到父组件中仅引用 this.refs.tagList.clientHeight 一次,即使在子组件更新后也不会重新计算
这里使用的是 React 14.7 版本,所以不能使用 hooks
class ChildComponent extends Component {
componentDidMount() {
this.doCalculating()
}
doCalculating = () => {
const defaultHeight = 50
const newHeight = this.refs.tagList.clientHeight
if (newHeight > defaultHeight ) {
// do logic
}
}
render() {
return (
<ul
ref={"tagList"}
>
{array.map((item, index) => (
<li key={index}>
<button>
{item}
<span onClick={
(e) => {
this.removeHandler()
this.doCalculating()
}
} ></span>
</button>
</li>
)
)}
</ul>
)
}
}
class ParentComponent extends Component {
actionFunc = () => {
// some logic
// call recalculate function, that always return initial value
this.responsesTags.doCalculating()
}
render() {
return (
<div>
<ChildComponent
ref={instance => { this.responsesTags = instance }}
/>
<button onClick={() => this.actionFunc()} />
</div>
)
}
}
在父组件中调用时重新计算函数缺少什么?
【问题讨论】:
-
您的代码似乎没问题。您可以为您的问题创建一个代码笔吗?
标签: javascript reactjs