2016-12-27 4 views
2

私はこれを行うことができることを知っている:反応成分のサイズを取得しますか?

<div ref='container' /> 

、その後

this.refs.container.getBoundingClientRect() 

をしかしthis.refs.thumbnailは、HTMLオブジェクトを返しませんので、私はこの

import Thumbnail from 'react-bootstrap/lib/Thumbnail' 
<Thumbnail ref='thumbnail' /> 
this.refs.thumbnail.getBoundingClientRect() 

を行うことはできません。サムネイルのサイズを取得するにはどうすればよいですか?

答えて

1

これを行うには汚い方法です。コンポーネントにラッピング要素の参照があり、関数型propを使用してサイズを設定します。

以下は例として実装されていますが、必要に応じて実装を変更することがあります。

class ComponentWhichNeedsInfo extends Component { 

constructor(props){ 
    super(props) 
    this.state = { sizes : {} } 
    this.setSize = this.setSize.bind(this) 
} 

setSize(elUniqueName, size){ 
    this.setState({ sizes[elUniqueName] : size }) 
} 

render(){ 
    return (
    <div> 
     <Thumbnail 
     uniqueName="thumbnail1" 
     setSize={this.setSize} 
     /> 
    </div> 
    ) 
} 

} 

class Thumbnail extends Component { 
static propTypes = { 
    setSize : PropTypes.func, 
    uniqueName : PropTypes.string 
} 
componentDidMount(){ 
    let { setSize } = this.props 
    if(this.props.setSize){ 
    let { uniqueName } = this.props 
    setSize(uniqueName, this.parentNodeEl.getBoundingClientRect()) 
    } 
} 
render(){ 
    return (
    <div ref={ node => { this.parentNodeEl = node } } > 
     ... 
    </div> 
    ) 
} 

} 

さらに、サイズの代わりに親要素に要素refを渡すこともできます。