// inheritance
class UrlLoader extends React.Component {
state = {
loading: false,
result: null,
error: null,
};
componentDidMount() {
this.setState({
loading: true,
});
this.load().then(
(result) => {
this.setState({
result,
loading: false,
});
},
(error) => {
this.setState({
error,
loading: false,
});
},
);
}
load() {
return fetch(this.props.url);
}
render() {
const { loading, error, result } = this.state;
if (loading) {
return 'Loading...';
}
if (error) {
return (
<div className="error">
{error}
</div>
);
}
return (
<div className="page-result">
{result}
</div>
);
}
}
class FancyUrlLoader extends UrlLoader {
componentDidMount() {
super.componentDidMount();
this.doSomethingElse();
}
doSomethingElse() {
// something else
}
render() {
const result = super.render();
return (
<div className="super-fancy">
{result}
</div>
);
}
}
// somewhere
const MyComponent = () => {
return (
<div>
<FancyUrlLoader url="https://google.com" />
</div>
);
};
// composition
class UrlLoader extends React.Component {
state = {
loading: false,
result: null,
error: null,
};
componentDidMount() {
this.setState({
loading: true,
});
this.load().then(
(result) => {
this.setState({
result,
loading: false,
});
},
(error) => {
this.setState({
error,
loading: false,
});
},
);
}
load() {
return fetch(this.props.url);
}
render() {
const { loading, error, result } = this.state;
let render;
if (loading) {
render = 'Loading...';
} else if (error) {
render = (
<div className="error">
{error}
</div>
);
} else {
render = (
<div className="page-result">
{result}
</div>
);
}
return this.props.children(render);
}
}
class FancyMaker extends React.Component {
componentDidMount() {
this.doSomethingElse();
}
doSomethingElse() {
// something else
}
render() {
return (
<div className="super-fancy">
{this.props.children}
</div>
);
}
}
// somewhere
const MyComponent = () => {
return (
<div>
<UrlLoader url="https://google.com">
{(children) => (
<FancyMaker>
{children}
</FancyMaker>
)}
</UrlLoader>
</div>
);
};
// 70 chars
import React from 'react';
export class Foo extends React.Component {};
// 79 chars
import React, { Component } from 'react';
export class Foo extends Component {};
class App extends React.Component {
constructor(props) {
super(props);
this.justAdd = this.justAdd.bind(this);
}
justAdd() {
// your logic
}
}
class App extends React.Component {
// option 2
justAdd = () => {
// your logic,
};
}
devServer: {
historyApiFallback: true
}
class Textarea extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.setState({
height: e.target.scrollHeight
});
}
render() {
const { height } = this.state;
return (
<div>
<textarea
name="text"
style={{ height }}
placeholder="Autoresize textarea"
onChange={this.onChange}
/>
</div>
)
}
}
.SomeClass {
&-foo { // < Такого в спецификации нет!
}
}
.App {
text-align: center;
&.gg { // < работает
color: #1e90ff;
}
}