话不多说,上代码:
1、this.refs.**.clientHeight就可以获取到当前组件的高度
//this.refs.**.clientHeight获取到当前组件的高度
class Category extends Component{
toggle=()=>{
if(this.refs.category.clientHeight>74){//获取当前组件的高度
/* 具体操作 */
}
}
render(){
return (
<div ref="category">
<a onClick={()=>{this.toggle()}}>
展开<Icon type="up" />
</a>
</div>
);
}
}
export default Category;
注:UI组件中不能使用ref。
2、使用 ref 来获取组件的引用
//点击按钮获取输入框的焦点
class MyComponent extends React.Component {
handleClick() {
// 使用原生的 DOM API 获取焦点
this.refs.myInput.focus();
}
render() {
// 当组件插入到 DOM 后,ref 属性添加一个组件的引用于到 this.refs
return (
<div>
<input type="text" ref="myInput" />
<input
type="button"
value="点我输入框获取焦点"
onClick={this.handleClick.bind(this)}
/>
</div>
);
}
}
3、ref的另一种写法
const { Tag, Input, Tooltip, Icon } = antd;
class EditableTagGroup extends React.Component {
state = {
inputVisible: false,
inputValue: '',
};
handleInputChange = e => {
this.setState({ inputValue: e.target.value });
};
showInput = () => {
this.setState({ inputVisible: true }, () => this.input.focus());
};
saveInputRef = input => (this.input = input);
render() {
const { tags, inputVisible, inputValue } = this.state;
return (
<div>
<Input
ref={this.saveInputRef}
type="text"
size="small"
style={{ width: 78 }}
value={inputValue}
onChange={this.handleInputChange}
/>
<Tag onClick={this.showInput} style={{ background: '#fff', borderStyle:
'dashed' }}>
<Icon type="plus" /> New Tag
</Tag>
</div>
);
}
}
ReactDOM.render(<EditableTagGroup />, mountNode);