从父组件获取子组件
例如:操作父组件使子组件获取焦点
子组件
一个输入框,带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>
)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。