react : 在组件内部获取组件本身

本文介绍了在React组件内部如何获取组件本身的实例,包括使用`this.refs`获取组件高度以及两种不同的ref使用方式,但需注意UI组件中不适用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话不多说,上代码:

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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值