我在我的项目中安装了一个名为 react-geosuggest 的 react-component。我需要找到 <label>
<Geosuggest>
中的 dom 元素组件并插入一个 onClick
处理程序到 <label>
.有没有办法针对 <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>
最佳答案
你必须使用 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);
关于javascript - 没有ref的 react 组件的目标dom元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40560846/