Skip to content

Instantly share code, notes, and snippets.

@amorkovin
Last active July 16, 2020 13:38
Show Gist options
  • Save amorkovin/c5c07b68e5fdaf519d20491923279681 to your computer and use it in GitHub Desktop.
Save amorkovin/c5c07b68e5fdaf519d20491923279681 to your computer and use it in GitHub Desktop.
Реакт: создание компонента
// ------------------------src/index.js-----------------------
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App propsapptest="Передаю этот текст в props">Отправляю текст в children данного компонетнта</App>
</React.StrictMode>,
document.getElementById('root')
);
// --------------------------src/App.js--------------------------
import React from 'react';
import HomePage from './pages/Home';
// Это функциональный компонент. Он умеет только отображать что либо. Аргументом передаются пропсы.
function App( { propsapptest, children } ) {
return (
<>
<div>Текст пришел из children: {children}</div>
<div>Это значение выводится из пропса функционального компонента: {propsapptest}</div>
<HomePage testprops="tst">Это текст для children компонетнат HomePage</HomePage>
</>
);
}
export default App;
// ------------------src/pages/Home/index.js-----------------------
import React, { Component } from "react";
// Обычные стили без модульности
import './HomePage.css';
// css-модуль
import s from './HomePage.module.css';
// Вставка изображения
import TestImg from './img/test.png';
// Svg можно вставлять как обычную картинку, а можно по особенному, как показано ниже.
import { ReactComponent as ReactLogoSvg } from './img/logo.svg';
const wordList = [
{
id: 1,
eng: 'test',
rus: 'тест'
},
{
id: 2,
eng: 'mom',
rus: 'мама'
},
{
id: 3,
eng: 'dad',
rus: 'папа'
}
];
// Классы используются, когда у компонента должно быть свое собственное изменяемое состояние.
class HomePage extends Component {
handleBtnClick = () => {
this.setState((state) => {
return {
btnIsClick: !state.btnIsClick,
}
});
}
render() {
// Достаю нужные props
// В children попадает то, что будет внутри тегов <HomePage testprops="tst">Это текст для children</HomePage>
const { testprops, children } = this.props;
const items = ['Item1', 'Item2', 'Item3'];
const marginRight = '20';
const listStyle = {
'marginLeft': '10px',
'marginRight': `${marginRight}px`,
'background': 'red',
};
return (
<>
<ul style={listStyle}>
<li>Это значение из пропсов: {testprops}</li>
{wordList.map(({ eng, rus, id }, index) => <li key={id}>{eng} : {rus}</li>)}
</ul>
{/*Картинка была импортирована import TestImg from './img/test.png';*/}
<img src={TestImg} alt="Тестовая картинка" />
{/*
Таким образом может быть вставлена картинка svg при новом особом ее импорте.
Благодаря такому импорту можно влить на любые теги svg при помощи css.
svg g { fill: reg; }
*/}
<ReactLogoSvg />
<div>Текст выводится из children: {children}</div>
<div className="wrapper">
<div className={s.text}>Это главная страница.</div>
<button type="button" onClick={this.handleBtnClick}>Кнопка</button>
</div>
</>
);
}
}
export default HomePage;
--------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment