如何将查询选择器限制为反应组件

How to limit queryselector to a react component

我有一个包含子组件列表的 React 组件。在子组件中,我想针对特定的 DOM 元素,例如,更改其 ComponentDidMount 方法中的颜色。我该怎么做?

父组件

export class ListComponent extends Component<...> {
    render(): ReactNode {
        return (
            <div>
                <ListItemComponent key="123"/>
                <ListItemComponent key="456"/>
                <ListItemComponent key="789"/>
            </div>
        );
    }
}

子组件

export class ListComponent extends Component<...> {
    componentDidMount(): void {
//      const elementToChange = document.queryselector(".toTarget");  // Only works for the first element as it only targets the first on the page
        const elementToChange = THISREACTCOMPONENT.queryselector(".toTarget");
        elementToChange.style.backgroundColor = "123123";
    }

    render(): ReactNode {
        return (
            <div>
                <div className="toTarget">
            </div>
        );
    }
}

所以,问题是,应该用什么代替 THISREACTCOMPONENT?如何在 React 组件中专门定位一个元素?

您可以使用 Document.querySelectorAll 来获取所有匹配的元素

document.querySelectorAll returns 匹配元素的数组。

那么你会这样做:

componentDidMount(): void {
  const elements = document.querySelectorAll(".toTarget");
  elements.forEach((el) => {
    el.style.backgroundColor = "123123";
  });
}

使用 React refRefs 已创建,因此您不必使用查询选择器,因为直接与 dom 交互可能会导致进一步的反应错误。

  export  class ListComponent extends Component<...> { {
      constructor(props) {
        super(props);
        this.myRef = React.createRef(); // Get a reference to a DOM element
      }
    componentDidMount(): void {
        const elementToChange = this.myref.current;
        elementToChange.style.backgroundColor = "123123";
    }
      render() {
        return (
            <div>
                <div className="toTarget"  ref={this.myRef}> // binds this element to the this.myref variable
            </div>
        )
      }
    }