Kõik, mida peaksite reageerimise kohta teadma: ehitamise alustamiseks vajalikud põhitõed

Kas olete Reacti vastu uudishimulik ja teil pole olnud võimalust seda õppida? Või äkki olete varem õpetusi proovinud, kuid olete selle põhikontseptsioonide omandamisel vaeva näinud? Või äkki olete õppinud põhitõed, kuid soovite oma teadmisi kinnistada? Mõlemal juhul on see artikkel mõeldud teile.
Ehitame lihtsa Reacti muusikapleieri, mis kihtides kulgeb uutele Reacti kontseptsioonidele.
Siit räägime:
- Mis on React komponent?
- ReactDOM renderdamine
- Klass vs funktsionaalsed komponendid
- JSX
- Osariik
- Ürituste korraldamine
- Asünkroonne setState
- Rekvisiidid
- Viited
See on peaaegu kõik, mida vajate rakenduse React loomiseks ja hooldamiseks. Kuid me tutvustame seda tükkhaaval.
Seadistamine
Olukord on selline: väike idufirma on teie poole pöördunud. Nad on loonud kasutajate jaoks lehe muusika üleslaadimiseks ja selle visualiseerimiseks helendavate värvidega. Kuid nad vajavad, et teete raske osa - AKA, et see toimiks.
Alustamiseks looge uus projektikataloog ja lisage järgmised kolm faili.
Veenduge, et kasutaksite selle juhendajaga Chrome'i ajakohast versiooni, vastasel juhul ei tööta ülaltoodud koodi animatsioonid.
Täname Steven Fabret esitusnupu CSS eest ja Justin Windle'i visualiseerimiskoodi eest (originaali saate vaadata siit).
Avage index.html
nii koodiredaktoris kui ka oma brauseris ja alustame!
Mis on React?
Reageerimine on viis kasutajaliideste loomiseks. See on seotud ainult sellega, mida näete esiplaanil. React muudab kasutajaliideste ehitamise väga lihtsaks, lõigates iga lehe tükkideks. Nimetame neid tükke komponentideks.
Siin on näide lehe komponentideks lõikamisest:

Kõiki ülal esile tõstetud jaotisi peetakse komponentideks. Kuid mida see arendaja jaoks tähendab?
Mis on React komponent?
React komponent on natuke koodi, mis tähistab tükki lehest. Iga komponent on JavaScripti funktsioon, mis tagastab koodilõigu, mis tähistab tükki veebilehte.
Lehe koostamiseks kutsume neid funktsioone kindlas järjekorras, paneme kokku tulemuse ja näitame seda kasutajale.
Kirjutame komponendi sisse
ag in inde
x.html wit
h th
e ty
pe of “text/
babel”:
function OurFirstComponent() { return ( // Code that represents the UI element goes here ); }
When we call the
OurFirstcomponent()
function, we will get back a piece of the page.
You can also write functions like this:
const OurFirstComponent = () => { return ( // Stuff to make this component goes here );}
React uses a language called JSX that looks like HTML but works inside JavaScript, which HTML usually doesn’t do.
You can add plain HTML to this section to make it appear on the UI:
function OurFirstComponent() { return ( Hello, I am a React Component!
); }
When we call the
OurFirstComponent()
function, we get back a bit of JSX. We can use something called ReactDOM to put it on the page.
function OurFirstComponent() { return ( Hello, I am a React Component!
); }
const placeWeWantToPutComponent = document.getElementById('hook'); ReactDOM.render(OurFirstComponent(), placeWeWantToPutComponent);
Now our
<
h1> tag will be put inside the element with the ID of
hook. It should look like this when you refresh your browser:

We can also write our component in JSX like so:
ReactDOM.render(, placeWeWantToPutComponent);
This is standard — invoke your components like you are writing HTML.
Putting Components Together
We can put React components inside other components.
function OurFirstComponent() { return ( I am the child!
); }
function Container() { return ( I am the parent!
); }
const placeWeWantToPutComponent = document.getElementById('hook'); ReactDOM.render(, placeWeWantToPutComponent);

This is how we build our page out of pieces of React — by nesting components inside of each other.
Class Components
So far, we’ve been writing components as functions. These are called functional components.
But you can write components another way, as JavaScript classes. These are called class components.
class Container extends React.Component { render() { return ( I am the parent!
); }}
const placeWeWantToPutComponent = document.getElementById('hook');ReactDOM.render(, placeWeWantToPutComponent);
Class components must have a function called render()
. The render function returns the JSX of the component. They can be used the same way as functional components, like this:
/>.
You should use functional components over class components because they’re easier to read, unless you need component state (more on that soon).
JavaScript in JSX
You can put JavaScript variables inside of your JSX like this:
class Container extends React.Component { render() { const greeting = 'I am a string!'; return ( { greeting }
); }}
Now the ‘I am a string!’ will be inside the h1
.
You can also do more difficult stuff, like call a function:
class Container extends React.Component { render() { const addNumbers = (num1, num2) => { return num1 + num2; }; return ( The sum is: { addNumbers(1, 2) }
); }}

JSX Gotchas
Rename OurFirstComponent()
to PlayButton
. We want it to return the following:
But there’s a problem: class
is a keyword in JavaScript, so we can’t use it. So how do we give our <
;a> a class o
f play?
Use a property called className
instead:
function PlayButton() { return ; }
class Container extends React.Component { render() { return ( ); } }
const placeWeWantToPutComponent = document.getElementById('hook'); ReactDOM.render(, placeWeWantToPutComponent);
What Is This Component Doing?
Class components can store information about their current situation. This information is called state
, which is stored in a JavaScript object.
In the code below, we have an object representing our components state. It has a key
of isMusicPlaying
which has a value
of false
. This object is assigned to this.state
in the constructor
method, which is called when the class is first used.
class Container extends React.Component { constructor(props) { super(props); this.state = { isMusicPlaying: false }; } render() { return ( ); }}
A constructor
method of a React component always needs to call super(props)
before anything else.
Okay, so what do we do with state
? Why does it exist?
Changing Our React Component Based On State
State is way to update our UI based on events.
In this tutorial, we will use state to change the play button from paused to playing based on the user clicking the play button.
When the user clicks on the button, the state will update, which will then update the UI.
Here’s how we get started. We can look at the component state with this.state
. In the following code, we look at the state and use it to decide what text to present to the user.
class Container extends React.Component { constructor(props) { super(props); this.state = { isMusicPlaying: false }; }
render() { const status = this.state.isMusicPlaying ? 'Playing' : 'Not playing'; return ( { status }
); }}
In the render function, this
is always referring to the component it is within.

But that’s not very useful unless we have a way to change this.state.isMusicPlaying
.
When Stuff Happens to Our Component
The user can interact with our components by clicking on the play button. We want to react (ha… ha…) to those events.
We do that through functions that take care of events. We call these event handlers.
class Container extends React.Component { constructor(props) { super(props); this.state = { isMusicPlaying: false }; }
handleClick(event) { // Do something about the click };
render() { let status = this.state.isMusicPlaying ? 'Playing :)' : 'Not playing :('; return ( { status }
); }}
When the user clicks on the h1
, our component will make the handleClick
function run. The function gets the event object as the argument, which means it can use it if it wanted to.
We use the .bind
method on handleClick
to make sure this
refers to the whole component, rather than just the h1
.
What This Component Should Be Doing
When we change the state of our component, it will call the render function again.
We can change state with this.setState()
, if we give it a new object representing the new state.
Our component on the page will always represent its current state. React does that for us.
handleClick() { if (this.state.isMusicPlaying) { this.setState({ isMusicPlaying: false }); } else { this.setState({ isMusicPlaying: true }); } };
But clicking an h1
isn’t as good as clicking our actual play button. Let’s make that work.
Talking Between Components
Your components can talk to each other. Let’s try it.
We can tell PlayButton
whether or not the music is playing using something called props
. Props are information shared from a parent component to a child component.
Props in JSX look the same as HTML properties.
We give PlayButton
a prop called isMusicPlaying
, which is the same as the isMusicPlaying
in this.state
.
class Container extends React.Component { constructor(props) { super(props); this.state = { isMusicPlaying: false }; }
handleClick() { if (this.state.isMusicPlaying) { this.setState({ isMusicPlaying: false }); } else { this.setState({ isMusicPlaying: true }); } };
render() { return ( ); }}
When the state of Container
changes, PlayButton
prop will change too, and the PlayButton
function will be called again. That means our component will update on the screen.
Inside PlayButton
, we can react to the change, because PlayButton
gets the props as an argument:
function PlayButton(props) { const className = props.isMusicPlaying ? 'play active' : 'play'; return ;}
If we change our state to this.state = { isMusicPlaying: true };
and reload the page, you should see the pause button:

Events as Props
Your props don’t have to be just information. They can be functions.
function PlayButton(props) { const className = props.isMusicPlaying ? 'play active' : 'play'; return ;}
class Container extends React.Component { constructor(props) { super(props); this.state = { isMusicPlaying: false }; }
handleClick() { if (this.state.isMusicPlaying) { this.setState({ isMusicPlaying: false }); } else { this.setState({ isMusicPlaying: true }); } };
render() { return ( ); }}
Now, when we click on the PlayButton
, it’ll change the state of Container
, which will change the props
of PlayButton
, which will cause it to update on the page.
The Bad Thing About setState
setState
is bad because it doesn’t do stuff right away. React waits a bit to see if there are more changes to make, then it does the state changes.
That means you don’t know for sure what your state will be when you call setState
.
So you shouldn’t do this:
handleClick() { this.setState({ isMusicPlaying: !this.state.isMusicPlaying });};
If you are changing your state based on the old state, you need to do things differently.
You need to give setState
a function, not an object. This function gets the old state as an argument, and returns an object that is the new state.
It looks like this:
handleClick() { this.setState(prevState => { return { isMusicPlaying: !prevState.isMusicPlaying }; });};
It is more difficult, but only needed when you are using the old state to make the new state. If not, you can just give setState
an object.
What Are Refs?
Let’s make some music happen.
First, we add an
io> tag:
class Container extends React.Component { constructor(props) { super(props); this.state = { isMusicPlaying: false }; }
handleClick() { this.setState(prevState => { return { isMusicPlaying: !prevState.isMusicPlaying }; }); };
render() { return ( ); }}
We need a way to get that
io> tag and call e
ither
play
() or p
ause() on it. We could do it
with document.getElementById('audio').
play() but there’s a better React way.
We give it a prop called ref
, which gets called with the
io> element as the first argument. It takes
that &
lt;audio> element and as
signs it t
o this.audio.
{ this.audio = audioTag }} />
This function will be called every time the Container
renders, which means this.audio
will always be up to date, and equal the
io> tag.
We then can play and pause the music:
handleClick() { if (this.state.isMusicPlaying) { this.audio.pause(); } else { this.audio.play(); } this.setState(prevState => { return { isMusicPlaying: !prevState.isMusicPlaying }; });};
Upload a music file (preferably an mp3 file) using the Choose files
button and hit play, and watch it go!
Moving Outside of Index.html
As you might have guessed, our React shouldn’t live forever inside a
pt>tag.
React takes a lot of build configuration. Fortunately, tools like Create React App take care of all that for you.
Install it to create your own React project. Follow their brief tutorial and start editing the JavaScript inside the src
directory, applying all the React knowledge you learned here!
Congratulations!
You can now make React things.
Next, check out a couple of articles for more information. One is about React best practices, the other about a useful part of React called lifecycle methods.
If you learned something from this article, please click those clappin’ hands, and share it with your friends.
You can also follow me on Medium and Twitter.