使用React中的Refs可以实现该功能。首先,在要引用组件的类上设置Ref:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return ;
}
}
接下来,可以通过该组件的key从Ref对象中检索该组件并进行任何操作:
const myComponent = this.myRef.current;
// Do something with the component here, such as:
myComponent.style.backgroundColor = 'red';
通过Refs获取组件可以方便地对其进行操作,但请注意,Refs应该尽量避免使用,因为它们打破了React的单向数据流模型。
上一篇:按其ID删除行中的特定DIV
下一篇:按其名称查找C#线程