【问题标题】:How to limit queryselector to a react component如何将查询选择器限制为反应组件
【发布时间】:2021-11-07 11:39:30
【问题描述】:

我有一个带有子组件列表的反应组件。在子组件中,我想定位一个特定的 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 组件中专门定位一个元素?

【问题讨论】:

    标签: reactjs typescript components queryselector


    【解决方案1】:

    使用反应refRefs 已创建,因此您不必使用 queryselector,因为直接与 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>
            )
          }
        }
    

    【讨论】:

    • 看起来很有趣!但是,当我尝试它时,我收到一个错误Property 'querySelector' does not exist on type 'RefObject&lt;unknown&gt;'。我想我需要将 unknown 更改为其他内容,但是什么?
    • 更新答案,添加'current' 不需要使用querySelector,this.myref.current 是元素
    【解决方案2】:

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

    document.querySelectorAll 返回匹配元素的数组。

    那么你会这样做:

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

    【讨论】:

    • 那么你会在父组件的componentDidMount方法中设置颜色吗?这确实是一个解决方案。如果可能的话,我仍然想包含子组件的逻辑。尽管如此,如果没有其他解决方案出现,我将保留此解决方案作为选项!谢谢!
    • 是的,我更新了答案。但是我想知道为什么你需要在你的componentDidMount 中设置它而不是直接在 JSX 中定义它?
    • "123123" 应该是一个有效的颜色,只是为了提醒你。
    • 我希望将元素的颜色更改为其子元素之一的相同颜色。但是,这些子元素作为 ReactFragment 作为道具传递,并且在它们被渲染之前我真的无法访问它(afaik)
    • 哦,我明白了,试试我的答案,看看它是否适合你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 2014-09-23
    相关资源
    最近更新 更多