内容简介:You still remember this comic fromlast post, right? I hope it’s left a lasting impression on you since it’s a really useful metaphor for thinking about React.In this post, we’re going to dive deeper into this topic. We’ll focus on a different tag,
You still remember this comic fromlast post, right? I hope it’s left a lasting impression on you since it’s a really useful metaphor for thinking about React.
In this post, we’re going to dive deeper into this topic. We’ll focus on a different tag, <input>
, to complete our mental model.
BTW: Stuck at home? Why don’t you join ournew challenge? Come learn React, meet like-minded people (with guaranteed social distance), build something cool and win prizes!
Moving on to input
Let’s look at this component:
function App() { return ( <div> <input type="text" /> </div> ) }
It’s going to render a text box in the browser. Compared to the div
or span
we used before, input
is special since it’s interactive — it allows a user to change its content.
Let me ask you three questions.
Question 1
First we add a button. When the button is clicked, we want to show an alert that contains the text in the text box.
function App() { return ( <div> <input type="text" /> <button onClick={ function() { // TODO alert(text in the input) } }>Send</button> </div> ) }
How would we get the text that a user would enter into this text box?
If you are wondering how to get the reference of that input, THINK AGAIN!
Remember, always look at the data!
Right now, we only have a static structure in the component. There’s no {}
at all. We need to add the data and cut a hole somewhere:
function App() { const [draft, setDraft] = React.useState("") return ( <div> <input type="text" value={draft} /> <button onClick={ function() { // TODO alert(text in the input) } }>Send</button> </div> ) }
So, how would we get the text of the text box? We should look at the value of draft
:
<button onClick={ function() { alert(draft) } }>Send</button>
In fact, “what’s the text in the text box” is almost the wrong question. What we should ask is “what’s behind the hole”, or “what’s the data that’s bound to the text box”.
From this example, we also see that we can cut holes in an attribute’s value, in addition to the content of a tag. But that’s it. There are no other places where we could cut holes.
<input value={text} /> // :white_check_mark: Correct <div>:muscle:{who}:facepunch:</div> // :white_check_mark: Correct <span>:muscle:{who}{action}</span> // :white_check_mark: Correct <input {attr}="1" /> // :x: Wrong <{tagName} /> // :x: Wrong
Question 2
Let’s use a different button. How would we change the text in the text box when the user clicks the button?
function App() { const [draft, setDraft] = React.useState("") return ( <div> <input type="text" value={draft} /> <button onClick={ function() { //TODO set the content of the textbox to ":heart_eyes:" } }>:heart_eyes:</button> </div> ) }
Again, if you want to do something like below, wrong answer.
$('input').val(':heart_eyes:')
Remember, always look at the data!
Since the input is bound to text
via value={text}
, we just need to change the data, and the text box will update itself:
setText(":heart_eyes:")
So the result would be like this:
Question 3
The emoji buttons above work fine. However, if you try to type in the text box, you’ll see that it doesn’t work at all! Try it above.
Why?
Let’s check out the code again:
function App() { const [draft, setDraft] = React.useState("") return ( <div> <input type="text" value={draft} /> <button onClick={ function() { setDraft(":heart_eyes:") } }>:heart_eyes:</button> </div> ) }
You see, the value of the input is determined by who’s behind the hole, i.e. the value of draft
. The only way to change draft
is by calling setDraft
. The only moment we call setDraft
is when the button is clicked. It doesn’t cover the situation when a user types in the text box!
To make the input work, we need to call setDraft
when a user types something into the text box:
<input type="text" value={draft} onChange={ function(event) { setDraft(event.target.value) } }/>
Here, event.target.value
is whatever the user types in the text box.
Recap
We’ve looked at <input>
as another example,
- to retrieve its value, we look at the data bound to the input
- to update its value, we look at the data too.
- the only way to change the data is to call the
setXXX
function. In theinput
, if it’s bound to some data, we need to explicitly callsetXXX
inonChange
. Otherwise a user won’t be able to type in anything.
When the input
has its value bound to a data item, i.e. the state, we call it a controlled component . We have similiar stories for other interactive HTML elements, such as select
and textarea
.
You might ask, are there uncontrolled components ? You guess it right. I’ll cover more about controlled and uncontrolled components in a future post.
But let’s do some work out first! :point_down:
Quiz Time!
How about doing some Kung Fu routines with Panda? Try the slider and button below:
:muscle::panda_face: :facepunch:
Punch:
Your Tasks
- Use this tarter project
- When the “show” button is clicked, show the current value of the slider in an alert dialog.
- When the slider moves, change the size of Panda’s fist accordingly.
- When you are done,the URL of your sandbox to win some hearts! Remember to save your file before copying the URL.
Hints
- What’s that
{ fontSize: 40 }
in the starter project? (Hint: it’s a JavaScript thing.) - Why are there two layers of
{}
aroundfontSize: 40
? - Try changing the number after
fontSize
, how would you make it dynamic? - Instead of
event.target.value
, you’ll need to useevent.target.valueAsNumber
. Otherwise the code won’t work.
Solution
Got stuck? Here’s the solution . Promise me, don’t peek until you’ve tried your very best!
以上所述就是小编给大家介绍的《React Mental Models: Working with Input》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
数据库系统概念
Abraham Silberschatz、Henry F. Korth、S. Sudarshan / 杨冬青、马秀莉、唐世渭 / 机械工业 / 2006-10-01 / 69.50元
本书是数据库系统方面的经典教材之一。国际上许多著名大学包括斯坦福大学、耶鲁大学、得克萨斯大学、康奈尔大学、伊利诺伊大学、印度理工学院等都采用本书作为教科书。我国也有许多所大学采用本书以前版本的中文版作为本科生和研究生的数据库课程的教材和主要教学参考书,收到了良好的效果。 本书调整和新增内容:调整了第4版的讲授顺序。首先介绍SQL及其高级特性,使学生容易接受数据库设计的概念。新增数据库设计的专......一起来看看 《数据库系统概念》 这本书的介绍吧!