Answer the question
In order to leave comments, you need to log in
Do they do this in Reacte?
Question about best practices in React.
There is an ItemsList component that loops the Item component. Each Item consists of several divs, several of which should respond to a click.
In order not to fence the garden from onClicks, I hang one onClick handler, lowered from the App component, on the root Item element, and I pass any click on the Item, the event itself and the index of the clicked Item to the top.
export default class Item extends React.Component {
render() {
const { item, index, onClick } = this.props;
return (
<div className="item" onClick={e => onClick(index, e)}>
<div className="item-over">...</div>
<div className="item-main">
<div className="item-text">...</div>
<div className="item-hint">...</div>
<div className="item-extra">...</div>
</div>
</div>
);
}
}
onItemClick = (index, e) => {
switch (e.target.className) {
case "item-over":
console.log("Клинкнут блок над айтмом " + index);
break;
case "item-text":
console.log("Кликнут основной текст в айтеме " + index);
break;
case "item-hint":
console.log("Кликнут доп текст в айтиме " + index);
break;
case "item-extra":
console.log("Кликнут дополнительный блок а айтиме");
break;
default: {
}
}
};
<ItemsList items={items} onClick={this.onItemClick} />
Answer the question
In order to leave comments, you need to log in
It's not normal to do that. One of the goals pursued by the developers of modern frameworks is to avoid the need to manually check with DOM selectors.
Places like this are the source of a whole class of bugs when you forget that a selector is used in JS and rename or remove it. And they will find out that something has fallen off, perhaps only your users.
You can, of course, use additional selectors with prefixes: 'item__hint js--item__hint', but with the capabilities of modern frameworks, it is better and more convenient to refuse to check against DOM selectors and assign different listeners to different elements.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question