我正在尝试集成或创建一个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>)
}
})
Run Code Online (Sandbox Code Playgroud)
我测试了这种方式设置风格,它会起作用,但是高度不是.
编辑:小提琴:
any*_*yab 16
回答有点晚,但从技术上讲,你可以通过这种方式得到元素:
var node = ReactDOM.findDOMNode(this.refs[ref-name]);
if (node){
var calculatedHeight = node.clientHeight;
}
Run Code Online (Sandbox Code Playgroud)
And*_*y_D 13
根据当前的React文档,refs的首选用法是传递一个回调而不是一个字符串,以便在this.refs的其他地方访问.所以要获得div的高度(在React.Component类中):
componentDidMount() {
this.setState({ elementHeight: this.divRef.clientHeight });
}
render() {
return <div ref={element => this.divRef = element}></div>
}
Run Code Online (Sandbox Code Playgroud)
或者它以这种方式工作,但我不知道这是否可取,因为我们在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>;
}
Run Code Online (Sandbox Code Playgroud)
参考:https://facebook.github.io/react/docs/more-about-refs.html
以下是使用refs和clientWidth/ 的示例clientHeight:
import React, { Component } from 'react';
import MyImageSrc from './../some-random-image.jpg'
class MyRandomImage extends Component {
componentDidMount(){
let { clientHeight, clientWidth } = this.refs.myImgContainer;
console.log(clientHeight, clientWidth);
}
render() {
return (
<div ref="myImgContainer">
<img src={MyImageSrc} alt="MyClickable" />
</div>
);
}
}
export default MyRandomImage;
Run Code Online (Sandbox Code Playgroud)
注意:这似乎width可靠,但不是height.如果我发现修复,我会编辑...
不知道其他人,但我总是必须在下一个刻度上得到它,以确保获得正确的高度和宽度.感觉很讨厌,但猜测它与渲染周期有关,但我现在就把它拿走.onLayout在某些用例中可能会更好.
componentDidMount() {
setTimeout(() => {
let ref = this.refs.Container
console.log(ref.clientHeight)
console.log(ref.clientWidth)
}, 1)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70685 次 |
| 最近记录: |