const checked = Array.from(document.querySelectorAll('.btn:checked'), n => n.value);
const filtered = arr.filter(n => checked.includes(n));
var arr = [
{ country: 'Italy', capital: "rome"},
{ country: 'usa', capital: 'Washington'},
{ country: 'france', capital: 'Paris'},
{ country: 'spain', capital: 'Madrid'},
]
const onClick = () => {
const countriesChecked = Array.from(document.querySelectorAll('.btn') )
.filter(item => item.checked)
.map(item => item.value)
const cities = arr
.filter(elem => countriesChecked.includes(elem.country))
.map(elem => elem.capital)
alert(cities)
}
[...document.querySelectorAll('.btn')].forEach(item => {
item.addEventListener('click', onClick)
})
document - текущий документ
getElementById() - метод получения элемента используя id
onchange - свойство элемента для обработчика события
function (event){} - анонимная функция (обработчик события)
event - локальная переменная в контексте анонимной функции
target - таргет он и в африке таргет (целевой элемент, где происходит туса)
parentNode - родительская нода
childNodes[1] - у родителя есть дети
data - у детей есть данные
slice(1) - отхренашить кусочек
currentKey - отхренашеный кусочек
class Slider extends Component {
state = {
active: 0
};
componentDidMount() {
const { items } = this.props;
this.timeout = setTimeout(
() => this.updateActive(this.state.active, 1, items.length),
5000
);
}
componentDidUpdate(prevProps, prevState) {
const { items } = this.props;
const { active } = this.state;
if (
prevState.active !== active ||
prevProps.items.length !== items.length
) {
clearTimeout(this.timeout);
this.timeout = setTimeout(
() => this.updateActive(active, 1, items.length),
5000
);
}
}
componentWillUnmount() {
clearInterval(this.timeout);
}
updateActive = (active, step, length) => {
this.setState({
active: step ? (active + step + length) % length : active
});
};
next = e =>
this.setState({
active: this.updateActive(
this.state.active,
+e.target.dataset.step,
this.props.items.length
)
});
goTo = e => this.updateActive(+e.target.dataset.index);
render() {
const { active } = this.state;
const { items } = this.props;
const { length, [active]: slide } = items;
return (
<div>
<div className="slideshow-container">
<div className="mySlides fade">
<div className="numbertext">
{active + 1} / {length}
</div>
<img src={slide.img} />
<div className="text">{slide.title}</div>
</div>
<a className="prev" onClick={this.next} data-step={-1}>
❮
</a>
<a className="next" onClick={this.next} data-step={+1}>
❯
</a>
</div>
<div className="dots">
{items.map((n, i) => (
<span
key={n.id}
className={`dot ${i === active ? "active" : ""}`}
onClick={this.goTo}
data-index={i}
/>
))}
</div>
</div>
);
}
}
class TabContent extends React.Component {
render() {
const { title, content } = this.props;
return (
<div className="tabcontent">
<h3>{title}</h3>
<p>{content}</p>
</div>
);
}
}
class Tabs extends React.Component {
state = {
active: null,
}
openTab = e => this.setState({
active: +e.target.dataset.index,
});
render() {
const { items } = this.props;
const { active } = this.state;
return (
<div>
<div className="tab">
{items.map((n, i) => (
<button
className={`tablinks ${i === active ? 'active' : ''}`}
onClick={this.openTab}
data-index={i}
>{n.title}</button>
))}
</div>
{items[active] && <TabContent {...items[active]} />}
</div>
);
}
}
const Element = props => {
const [styleEnabled, setStyle] = useState(false);
return (
<div
className={`myDIV ${styleEnabled ? "mystyle" : ""}`}
onClick={e => setStyle(!styleEnabled)}
>
Toggle me
</div>
);
};
// class component example
class Example extends React.Component {
state = {
isActive: false,
};
render() {
const { isActive } = this.state;
return (
<div>
<button>Try it</button>
<div>
This is a DIV element.
</div>
</div>
);
}
}
// functional component example
const Example = () => {
const [isActive, setIsActive] = useState(false);
return (
<div>
<button>Try it</button>
<div>
This is a DIV element.
</div>
</div>
);
}
// class component example
class Example extends React.Component {
state = {
isActive: false,
};
handleClick = () => {
};
render() {
const { isActive } = this.state;
return (
<div>
<button onClick={this.handleClick}>Try it</button>
<div>
This is a DIV element.
</div>
</div>
);
}
}
// functional component example
const Example = () => {
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
};
return (
<div>
<button onClick={handleClick}>Try it</button>
<div>
This is a DIV element.
</div>
</div>
);
}
// class component example
class Example extends React.Component {
state = {
isActive: false,
};
handleClick = () => {
this.setState(state => ({ isActive: !state.isActive }));
};
render() {
const { isActive } = this.state;
return (
<div>
<button onClick={this.handleClick}>Try it</button>
<div>
This is a DIV element.
</div>
</div>
);
}
}
// functional component example
const Example = () => {
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
setIsActive(s => !s);
};
return (
<div>
<button onClick={handleClick}>Try it</button>
<div>
This is a DIV element.
</div>
</div>
);
}
// class component example
class Example extends React.Component {
state = {
isActive: false,
};
handleClick = () => {
this.setState(state => ({ isActive: !state.isActive }));
};
render() {
const { isActive } = this.state;
return (
<div>
<button onClick={this.handleClick}>Try it</button>
<div className={isActive ? 'mystyle' : ''}>
This is a DIV element.
</div>
</div>
);
}
}
// functional component example
const Example = () => {
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
setIsActive(s => !s);
};
return (
<div>
<button onClick={handleClick}>Try it</button>
<div className={isActive ? 'mystyle' : ''}>
This is a DIV element.
</div>
</div>
);
}
const TabContent = ({ content }) => (
<div className="accordion">
<p>{content}</p>
</div>
);
function Tabs({ items }) {
/* (1) Добавлено значение по-умолчанию для активной вкладки */
const [active, setActive] = React.useState(0);
/* (2) Хандлер по-хорошему не должен ничего возвращать */
const openTab = e => {
setActive(+e.target.dataset.index);
};
return (
<div>
<div className="tab">
{items.map((n, i) => (
<button
/* (3) Добавлено свойство key */
key={i}
className={`tablinks${i === active ? ' active' : ''}`}
onClick={openTab}
data-index={i}
>
{n.title}
</button>
))}
</div>
{items[active] && <TabContent {...items[active]} />}
</div>
);
}
/* (4) Добавлено свойство title для каждого пункта */
/* (5) Добавлены открывающие кавычки для значений content */
const items = [
{
title: 'First',
content:
'1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
},
{
title: 'Second',
content:
'2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
},
{
title: 'Third',
content:
'3. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
}
];
ReactDOM.render(<Tabs items={items} />, document.getElementById('app'));
const items = [
{ title: 'London', content: 'London is the capital city of England.' },
{ title: 'Paris', content: 'Paris is the capital of France.' },
{ title: 'Tokyo', content: 'Tokyo is the capital of Japan.' },
];
const TabContent = ({ title, content }) => (
<div className="tabcontent">
<h3>{title}</h3>
<p>{content}</p>
</div>
);
function Tabs({ items }) {
const [ active, setActive ] = React.useState(null);
const openTab = e => setActive(+e.target.dataset.index);
return (
<div>
<div className="tab">
{items.map((n, i) => (
<button
className={`tablinks ${i === active ? 'active' : ''}`}
onClick={openTab}
data-index={i}
>{n.title}</button>
))}
</div>
{items[active] && <TabContent {...items[active]} />}
</div>
);
}
/**
* какая-то функция, которая возвращает поле объекта name
* @returns {String}
*/
function getName () {
return this.name ? this.name : null;
}
var obj1 = {
name: 'name1',
getName: getName
}
var obj2 = {
name: 'name2',
getName: getName
}
// в данном случае, getName смотрит на obj1#name
console.log(obj1.getName()) // name1
// в данном случае, getName смотрит на obj2#name
console.log(obj2.getName()) // name2