加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react-bits:从父组件获取子组件

发布时间:2020-12-15 07:26:14 所属栏目:百科 来源:网络整理
导读:react-bits 原文 从父组件获取子组件 例如:操作父组件使子组件获取焦点 子组件 一个输入框,带focus()函数可以自动获取焦点 class Input extends Component { focus() { this .el.focus(); } render() { return ( input ref={el= { this .el = el; }} / );

react-bits
原文

从父组件获取子组件
例如:操作父组件使子组件获取焦点

子组件
一个输入框,带focus()函数可以自动获取焦点

class Input extends Component {
  focus() {
    this.el.focus();
  }

  render() {
    return (
      <input
        ref={el=> { this.el = el; }}
      />
    );
  }
}

父组件
在父组件内,通过ref获取子组件,并可调用其focus()函数

class SignInModal extends Component {
  componentDidMount() {
    // Note that when you use ref on a component,it’s a reference to
    // the component (not the underlying element),so you have access to its methods.
    this.InputComponent.focus();
  }

  render() {
    return (
      <div>
        <label>User name:</label>
        <Input
          ref={comp => { this.InputComponent = comp; }}
        />
      </div>
    )
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读