通过父组件去访问子组件. 比如一个能自动focus的输入框(通过父组件控制自动focus)
子组件是一个带有input标签和focus方法的组件. 其中focus方法能focus到对应的HTML元素上.
class Input extends Component {
focus() {
this.el.focus();
}
render() {
return (
<input
ref={el=> { this.el = el; }}
/>
);
}
}
在父组件中,我们能得到子组件的引用并且调用子组件的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>
)
}
}