- 深入某个组件内部
- 子组件
- 父组件
- 参考资料:
深入某个组件内部
通过父组件去访问子组件.
比如一个能自动focus的输入框(通过父组件控制自动focus)
子组件
子组件是一个带有input标签和focus方法的组件. 其中focus方法能focus到对应的HTML元素上.
class Input extends Component {focus() {this.el.focus();}render() {return (<inputref={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><Inputref={comp => { this.InputComponent = comp; }}/></div>)}}
参考资料:
- https://hackernoon.com/10-react-mini-patterns-c1da92f068c5
