2017-09-13 3 views
0

reactjs에서 요소의 높이를 다른 요소의 스타일로 사용하려면 어떻게해야합니까?reactjs에서 요소의 높이를 얻는 방법은 무엇입니까?

내 코드가 잘못 되었나요?

import React, { Component } from 'react'; 

import TextField from 'material-ui/TextField'; 

class Messages extends Component { 

    constructor(props) { 
     super(props) 

     this.state = { 
      height: 0 
     } 
    } 

    componentDidMount() { 
     const height = this.input.clientHeight; 
     this.setState({ height: height }); 
    } 

    render() { 
     const outputStyle = { 
      overflowY:'scroll', 
      height:`calc(100%-${this.state.height})` 
     }; 

     const inputStyle = { 
      position:'fixed', 
      bottom:'0', 
      height:'auto' 
     }; 

     return (
      <div style={{height:'100%'}}> 
       <div name="output" style={outputStyle}/> 
       <TextField name="input" multiLine={true} fullWidth={true} underlineShow={false} style={inputStyle} rows={2} ref={(input) => {this.input = input;}} /> 
      </div> 
     ); 
    } 
} 

export default Messages; 

제 목표는 "출력"요소의 높이를 100 % - this.state.height로 정의하는 것입니다.

+1

'setState' 다음에'this.state'를 호출하면 여전히 초기 값을 얻을 수 있습니다. render 메소드 내에 log.console을 시도하십시오. 상태의 값을 보려면 – abdul

+0

'this.setState ({height : height},() => {console.log (this.state.height)}); '를 시도하고 로그 할 내용을 확인하십시오 – bennygenel

+0

"undefined "로그에 – juavenel

답변

0

setState는 비동기식이므로 호출 후 상태가 어떻게 든 올바르게 업데이트됩니다. 그러면 렌더링이 다시 호출됩니다. 렌더링 또는 구성 요소 업데이트 상태에서 새 상태를 확인하십시오. https://facebook.github.io/react/docs/react-component.html#componentwillupdate

상태를 변경 한 후에는 절대로 변경하지 마십시오.

outputStyle.height를 this.state.height로 설정하기 만하면됩니다.

+0

, "undefined"가 나타납니다. – juavenel

1

사용자 지정 구성 요소에 대한 심판은 구성 요소 인스턴스가 아닌 DOM 노드를 반환

내가 사용해야합니다 : ReactDOM.findDOMNode (this.input) .clientHeight을;

관련 문제