React Mental Models: Working with Input

栏目: IT技术 · 发布时间: 4年前

内容简介: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,

React Mental Models: Working with Input

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 the input , if it’s bound to some data, we need to explicitly call setXXX in onChange . 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

  1. Use this tarter project
  2. When the “show” button is clicked, show the current value of the slider in an alert dialog.
  3. When the slider moves, change the size of Panda’s fist accordingly.
  4. When you are done,the URL of your sandbox to win some hearts! Remember to save your file before copying the URL.

Hints

  1. What’s that { fontSize: 40 } in the starter project? (Hint: it’s a JavaScript thing.)
  2. Why are there two layers of {} around fontSize: 40 ?
  3. Try changing the number after fontSize , how would you make it dynamic?
  4. Instead of event.target.value , you’ll need to use event.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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

娱乐至死

娱乐至死

[美] 尼尔·波兹曼 / 章艳 / 广西师范大学出版社 / 2011-6 / 29.80元

《娱乐至死》是对20世纪后半叶美国文化中最重大变化的探究和哀悼:印刷术时代步入没落,而电视时代蒸蒸日上;电视改变了公众话语的内容和意义;政治、宗教、教育和任何其他公共事务领域的内容,都不可避免的被电视的表达方式重新定义。电视的一般表达方式是娱乐。一切公众话语都日渐以娱乐的方式出现,并成为一种文化精神。一切文化内容都心甘情愿地成为娱乐的附庸,而且毫无怨言,甚至无声无息,“其结果是我们成了一个娱乐至死......一起来看看 《娱乐至死》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

MD5 加密
MD5 加密

MD5 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具