我正在尝试集成或创建https://github.com/kumailht/gridforms的React版本,为此,我需要规范化行中列的高度。原件采用网格行的高度,并将其应用于子列。
我曾计划获取行的高度,然后将其映射到孩子的属性,尽管从我的尝试来看,我认为这可能不是理想的方式,甚至不可能?
下面是我当前的代码。
GridRow = React.createClass({
render(){
const children = _.map(this.props.children, child => {
child.props.height = // somehow get row component height
return child
})
return (<div data-row-span={this.props.span} {...this.props}>
{children}
</div>)
}
})
GridCol = React.createClass({
render(){
return (<div data-field-span={this.props.span} style={{height:this.props.height}} {...this.props}>
{this.props.children}
</div>)
}
})
我测试了这样设置样式,它可以工作,但是获取高度不是这样。
编辑:小提琴:
发布于 2016-05-21 15:53:04
回答有点晚了,但从技术上讲,你可以通过这种方式获得元素高度:
var node = ReactDOM.findDOMNode(this.refs[ref-name]);
if (node){
var calculatedHeight = node.clientHeight;
}
发布于 2016-06-03 02:57:45
根据当前的React文档,refs的首选用法是传递给它一个回调,而不是要在this.refs中的其他地方访问的字符串。因此,要获取div的高度(在React.Component类中):
componentDidMount() {
this.setState({ elementHeight: this.divRef.clientHeight });
}
render() {
return <div ref={element => this.divRef = element}></div>
}
或者它是这样工作的,尽管我不知道这是否可取,因为我们在render方法中设置了state。
getHeight(element) {
if (element && !this.state.elementHeight) { // need to check that we haven't already set the height or we'll create an infinite render loop
this.setState({ elementHeight: element.clientHeight });
}
}
render() {
return <div ref={this.getHeight}></div>;
}
参考:https://facebook.github.io/react/docs/more-about-refs.html
发布于 2017-04-13 11:40:26
不知道其他人,但我总是必须在下一个刻度时得到它,以确保获得正确的高度和宽度。感觉有点老生常谈,但我猜测这与渲染周期有关,但我现在就接受它。在某些用例中,onLayout可能工作得更好。
componentDidMount() {
setTimeout(() => {
let ref = this.refs.Container
console.log(ref.clientHeight)
console.log(ref.clientWidth)
}, 1)
}
https://stackoverflow.com/questions/31661790
复制相似问题