React Mental Models: Working with Input

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

内容简介: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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Ruby元编程

Ruby元编程

[意] Paolo Perrotta / 廖志刚、陈睿杰 / 华中科技大学出版社 / 2012-1-10 / 56.00元

《Ruby元编程》以案例形式循序渐进讲解Ruby对象模型原理和高级应用技巧,堪称动态语言的设计模式。书中讲述的各种Ruby编程模式,完全可以应用于其他动态语言(甚至静态语言)。本书不仅适合Ruby程序员阅读,也适合对动态编程 语言和面向对象编程感兴趣的读者阅读。所有对程序设计理论感兴趣的人都能从中获益。Ruby之父松本行弘作序推荐。一起来看看 《Ruby元编程》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具