深入某个组件内部

优质
小牛编辑
142浏览
2023-12-01

通过父组件去访问子组件.
比如一个能自动focus的输入框(通过父组件控制自动focus)

子组件

子组件是一个带有input标签和focus方法的组件. 其中focus方法能focus到对应的HTML元素上.

  1. class Input extends Component {
  2. focus() {
  3. this.el.focus();
  4. }
  5. render() {
  6. return (
  7. <input
  8. ref={el=> { this.el = el; }}
  9. />
  10. );
  11. }
  12. }

父组件

在父组件中,我们能得到子组件的引用并且调用子组件的focus方法.

  1. class SignInModal extends Component {
  2. componentDidMount() {
  3. // Note that when you use ref on a component, it’s a reference to
  4. // the component (not the underlying element), so you have access to its methods.
  5. this.InputComponent.focus();
  6. }
  7. render() {
  8. return (
  9. <div>
  10. <label>User name:</label>
  11. <Input
  12. ref={comp => { this.InputComponent = comp; }}
  13. />
  14. </div>
  15. )
  16. }
  17. }

参考资料: