我尝试在 React Native 中使用以下代码:
...
_getContentHeight() {
if (this.refs.AccordionContent) {
this.refs.AccordionContent.measure((ox, oy, width, height, px, py) => {
// Sets content height in state
this.setState({
height: this.props.expanded ? height : 0,
content_height: height
});
});
}
},
componentDidMount() {
// Gets content height when component mounts
// without setTimeout, measure returns 0 for every value.
// See https://github.com/facebook/react-native/issues/953
setTimeout(this._getContentHeight);
// tried setTimeout(this._getContentHeight.bind(this);
},
...
现在,当我在 Chrome 中调试应用程序时,我发现我从未到达 _getContentHeight()
。现在我非常确定它必须通过异步调用等执行某些操作。但是有没有办法对此进行调试,并查看我获得的高度和 content_height
值是什么?
需要帮助,特别是在理解 setTimeout/异步函数调用方面。
最佳答案
我建议将对 measure
的调用移至 componentDidMount
内,以确保您的功能在抽象它并处理您可能遇到的任何范围或对象引用问题之前正常工作面对现在。
componentDidMount() {
this.refs.AccordionContent.measure((ox, oy, width, height, px, py) => {
// Sets content height in state
this.setState({
height: this.props.expanded ? height : 0,
content_height: height
});
});
}
更新:
我已将您的代码包装在一个 react 类中,并使测量对象出错@ https://jsfiddle.net/x7w62w99/
var Hello = React.createClass({
_getContentHeight() {
console.log(this.refs)
if (this.refs.AccordionContent) {
this.refs.AccordionContent.measure((ox, oy, width, height, px, py) => {
// Sets content height in state
this.setState({
height: this.props.expanded ? height : 0,
content_height: height
});
});
}
},
componentDidMount() {
setTimeout(this._getContentHeight);
},
render: function() {
return <div ref='AccordionContent'>
Hello {this.props.name}
<div id='AccordionContent'>
some stuff
</div>
</div>;
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
关于javascript - 函数未在 setTimeout 内执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36816222/