React获取组件的高度

时间:2019-05-29 13:26:10

标签: javascript reactjs

我需要知道另一个React组件中 React Component 的高度。我知道可以通过调用this.cmref.current.clientHeight来达到元素的高度。我正在寻找这样的东西:

子组件:

const Comp = () =>{
    return(
        <div>some other stuff here</div>
    )
}
export default Comp

父组件:

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    componentDidSomething(){
        const height = this.compref.current.clientHeight;
        //which will be undefined
    }
    render(){
        return(
            <div>
                <Comp ref={this.compref} />
            </div>
        )
    }
}

这可能吗?预先感谢。

2 个答案:

答案 0 :(得分:1)

您实际上需要引用子组件的div才能获得所需的元素,而不是子组件本身。为此,您可以将功能传递给孩子,然后孩子将其传递给div。下面的工作示例:

import textx


MyLanguage = """
    Model
        :   (locations+=Location)*
            (employees+=Employee)*
            (positions+=Position)*
            (projects+=Project)*
        ;

    Project
        :   'project' name=ID
            ('{'
                ('use' use=[Position])*
            '}')?
        ;

    Position
        :   'define' 'position' employee=[Employee|FQN] '->' location=[Location|FQN] ('as' name=ID)?
        ;

    Employee
        :   'employee' name=ID   
        ;

    Location
        :   'location' name=ID
            ( '{'
                (sub_location+=Location)+
            '}')?
        ;

    FQN
        :   ID('.' ID)*
        ;

    Comment:
      /\/\/.*$/
    ;                
"""

MyCode = """
    location Building
    {
        location Entrance
        location Exit
    }

    employee Hans
    employee Juergen

    // Shall be referred to with the given name: "EntranceGuy"
    define position Hans->Building.Entrance as EntranceGuy 
    // Shall be referred to with the autogenerated name: <Employee>"At"<LastLocation>
    define position Juergen->Building.Exit                  

    project SecurityProject
    {
        use EntranceGuy
        use JuergenAtExit
    }
"""


def position_name_generator(obj):
    if "" == obj.name:
        obj.name = obj.employee.name + "At" + obj.location.name


def main():
    meta_model = textx.metamodel_from_str(MyLanguage)
    meta_model.register_scope_providers({
        "Position.location": textx.scoping.providers.FQN(),
    })

    meta_model.register_obj_processors({
        "Position": position_name_generator,
    })

    model = meta_model.model_from_str(MyCode)
    assert model, "Could not create model..."


if "__main__" == __name__:
    main()
const Comp = (props) =>{
    return(
        <div ref={props.onRef}>some other stuff here</div>
    )
}

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    
    componentDidMount(){
        const height = this.compref.current.clientHeight;
        //which will be undefined --- No more!
        console.log('height: ', height);
    }
    
    onCompRef = (ref) => {
      this.compref.current = ref;
    }
    
    render(){
        return(
            <div>
                <Comp onRef={this.onCompRef} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.getElementById("root"));

答案 1 :(得分:1)

const Comp = React.forwardRef((props, ref) => (
  <div ref={ref}> some other stuff here </div>
));

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    componentDidMount(){
        const height = this.compref.clientHeight;
        console.log("hieght", height);
    }
    render(){
        return(
            <div>
                <Comp ref={(el) => this.compref = el} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.querySelector("#app"))     

您可以这样尝试吗?希望能帮助到你。请参阅转发引用https://reactjs.org/docs/forwarding-refs.html