【问题标题】:Target dom element of react component without ref没有参考的反应组件的目标dom元素
【发布时间】:2017-03-26 10:38:42
【问题描述】:

我在我的项目中安装了一个名为 react-geosuggest 的 react-component。我需要在<Geosuggest> 组件中找到<label> dom 元素并将onClick 处理程序插入<label>。有没有办法在不改变<Geosuggest> 组件代码的情况下定位<label> 标记。

这里是 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>

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你必须使用 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2017-11-24
      相关资源
      最近更新 更多