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