在没有ref的情况下定位React组件的目标DOM元素。

4
我在项目中安装了一个名为 react-geosuggest 的 React 组件。我需要找到 <Geosuggest> 组件中的 <label> DOM 元素,并向其插入一个 onClick 处理程序。是否有一种方法可以针对 <label> 标签进行定位,而不更改 <Geosuggest> 组件的代码。
以下是 JSX 代码:
render() {
return (
<div>
  <Geosuggest
    id = "searchbar"
    label = " "
    placeholder = ""
    initialValue = {this.state.location}
    onChange = {this.onInputChange}
    onSuggestSelect = {this.onSelection}
    onClick = {this.toggleSearch}
    className = {this.state.expand}
    inputClassName = {this.state.expand}
    // Name a calling reference
    ref = 'geosuggest_component'
  />
</div>
);

以下是HTML输出

<div class="geosuggest">
<div class="geosuggest__input-wrapper">
<label for="searchbar"></label>
<input class="geosuggest__input" type="text" id="searchbar">
</div>
</div>
1个回答

2

您需要使用vanillajs。在组件中,您可以在componentDidMount中访问geosuggest_component ref:

componentDidMount() {
    // findDOMNode returns an HTMLElement
    const node = ReactDOM.findDOMNode(this.refs.geosuggest_component);
    // Then search the label
    const label = node.querySelector('label');
    // Now, you can do anything you want with label
    label.addEventListener('click', () => console.log('clicked'))   
}

我使用ReactDOM.findDOMNode是因为在这种情况下,this.refs.geosuggest_component返回一个React组件。方法findDOMNode将给您所需的HTMLElement。
然而,更好的声明ref的方法是使用回调函数:
ref={node => this.geosuggest_component = node}

现在在componentDidMount方法中:
const node = ReactDOM.findDOMNode(this.geosuggest_component);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接