在React中,要访问同级组件的refs,可以通过使用回调函数或者React.createRef()来实现。
示例代码如下:
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.childRef = null;
}
getChildRef = (ref) => {
this.childRef = ref;
}
render() {
return (
<div>
<ChildComponent getRef={this.getChildRef} />
<button onClick={() => this.childRef.focus()}>Focus Child Component</button>
</div>
);
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.inputRef = null;
}
componentDidMount() {
this.props.getRef(this.inputRef);
}
render() {
return (
<input type="text" ref={(ref) => { this.inputRef = ref; }} />
);
}
}
在上面的例子中,ParentComponent通过getChildRef方法获取了ChildComponent的ref,并且在按钮的点击事件中调用了子组件的focus方法。
示例代码如下:
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}
render() {
return (
<div>
<ChildComponent ref={this.childRef} />
<button onClick={() => this.childRef.current.focus()}>Focus Child Component</button>
</div>
);
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
render() {
return (
<input type="text" ref={this.inputRef} />
);
}
}
在上面的例子中,ParentComponent通过React.createRef()创建了一个ref对象,并将其赋值给ChildComponent的ref属性。然后可以通过该ref对象的current属性访问子组件的实例,从而调用子组件的方法。
这是React中访问同级组件的refs的两种常用方法。这些方法可以帮助您在React应用程序中有效地访问和操作组件。
领取专属 10元无门槛券
手把手带您无忧上云