如何获取reactjs中元素的高度?
如何在reactjs中获取一个元素的高度,以便在另一个元素的样式中使用它 我的代码有什么问题如何获取reactjs中元素的高度?,reactjs,Reactjs,如何在reactjs中获取一个元素的高度,以便在另一个元素的样式中使用它 我的代码有什么问题 import React, { Component } from 'react'; import TextField from 'material-ui/TextField'; class Messages extends Component { constructor(props) { super(props) this.state = {
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;
import React,{Component}来自'React';
从“物料界面/文本字段”导入文本字段;
类消息扩展组件{
建造师(道具){
超级(道具)
此.state={
身高:0
}
}
componentDidMount(){
常量高度=this.input.clientHeight;
this.setState({height:height});
}
render(){
常量输出样式={
溢出:'scroll',
高度:`calc(100%-${this.state.height})`
};
常量输入样式={
位置:'固定',
底部:'0',
高度:'自动'
};
返回(
{this.input=input;}}/>
);
}
}
导出默认消息;
我的目标是通过以下方式定义元素“output”的高度:100%-this.state.height。setState是异步的,调用后您的状态将以某种方式正确更新。然后将再次调用render。尝试在render或componentWillUpdate中检查新状态: 你永远不应该在改变你的状态之后马上去寻找状态的改变
只需将outputStyle.height设置为this.state.height,就可以了。自定义组件上的引用将返回组件实例,而不是dom节点
我必须使用:ReactDOM.findDOMNode(this.input).clientHeight 在
setState
之后调用this.state
,仍然会得到初始值。在render方法中尝试log.console。查看stateTrythis.setState({height:height},()=>{console.log(this.state.height)})的值
看看这将要发生什么我在日志中得到了“未定义”这是因为this.input.clientHeight可能未定义this.input.clientHeight
这是从哪里来的?在渲染中,我得到了“未定义”