2016-11-12 35 views
2

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

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

你必须使用vanillajs。在你的组件,你可以在componentDidMount访问geosuggest_component裁判:

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返回一个作出反应的组成部分。 findDOMNode方法会给你你需要的HTMLElement。

然而,更好的方法来声明一个裁判是用回调:

ref={node => this.geosuggest_component = node} 

现在componentDidMount:

const node = ReactDOM.findDOMNode(this.geosuggest_component);