简体   繁体   English

setState 在反应和传递道具与功能

[英]setState in react and passing props with functions

i'm new to react and just got into the field of props and passing functions, and my task was to make the app work with the given component, I tried to fix it and I got in one of those moment when you fix something and you don't now what happened:)我是新手,刚进入道具和传递函数领域,我的任务是让应用程序与给定组件一起工作,我试图修复它,当你修复某些东西时,我遇到了其中一个时刻你现在不知道发生了什么:)

the issue was cutting part of the main code and make another component:问题是削减部分主要代码并制作另一个组件:

this is the main app code:这是主要的应用程序代码:

import React, { useState } from "react";
import ToDoItem from "./ToDoItem";
import InputArea from "./InputArea";

function App() {
  const [inputText, setInputText] = useState("");
  const [items, setItems] = useState([]);

  function handleChange(event) {
    const newValue = event.target.value;
    setInputText(newValue);
  }

  function addItem() {
    setItems(prevItems => {
      return [...prevItems, inputText];
    });
    setInputText("");
  }

  function deleteItem(id) {
    setItems(prevItems => {
      return prevItems.filter((item, index) => {
        return index !== id;
      });
    });
  }

  return (
    <div className="container">
      <div className="heading">
        <h1>To-Do List</h1>
      </div>
      <InputArea 
      inputText={inputText}
      onTyping={handleChange}
      addItem={addItem}
      />
      <div>
        <ul>
          {items.map((todoItem, index) => (
            <ToDoItem
              key={index}
              id={index}
              text={todoItem}
              onChecked={deleteItem}
            />
          ))}
        </ul>
      </div>
    </div>
  );
}

export default App;

and this is the component code:这是组件代码:

import React from "react";

function InputArea(props) {
  return (
    <div className="form">
      <input onChange={(e)=>{
        props.onTyping(e)
      }} type="text" value={props.inputText} />
      <button onClick={()=>{
        props.addItem()
      }}>
        <span>Add</span>
      </button>
    </div>
  );
}

export default InputArea;

so... the problem was to try passing the state of the input field from the main app to the component and I faced the issue of const newValue = event.target.value;所以...问题是尝试将输入字段的 state 从主应用程序传递到组件,我遇到了const newValue = event.target.value;的问题。 is not defined, and then I tried this in the component code <input onChange={(e)=>{ props.onTyping(e) }} before it was <input onChange={()=>{ props.onTyping() }} and somehow it works just fine and perfectly,?!, can someone please explain why and how did it worked?没有定义,然后我在组件代码<input onChange={(e)=>{ props.onTyping(e) }}之前尝试了这个<input onChange={()=>{ props.onTyping() }}并且不知何故它工作得很好,很完美,?!有人可以解释它为什么以及如何工作吗?

PS: I'm not good at writing questions so please any comment on the question is helpful to improve my structure, thank you. PS:我不擅长写问题,所以请对问题发表任何评论有助于改进我的结构,谢谢。

React has one-way data binding, that means, the state itself is the true source of change. React 具有单向数据绑定,这意味着 state 本身就是真正的变化源。 You can't change something in the input field and expect it to automatically update the state that field use(Such magic happens in Angular- two way data binding).您不能更改输入字段中的某些内容并期望它自动更新该字段使用的 state(这种魔法发生在 Angular-双向数据绑定中)。 With this in mind let's look into your code:-考虑到这一点,让我们看看你的代码: -

  <InputArea 
  inputText={inputText}
  onTyping={handleChange}
  addItem={addItem}
  />

This component has an input field whose value is decided from inputText prop which is a state in its parent component App .该组件有一个输入字段,其valueinputText属性决定,该属性是其父组件App中的 state。 So when you start typing in this input field, you would want to update the inputText state of the App component so that the changed props are passed to the InputArea component.因此,当您开始在此输入字段中输入内容时,您可能希望更新App组件的inputText state,以便将更改后的props传递给InputArea组件。 For facilitating this, you have passed handleChange aliased as onTyping as a prop.为方便handleChange ,您已将别名为 onTyping 的onTyping作为道具传递。 Now you bind this prop to your onChange handler on input field which triggers whenever you type in the field.现在,您将此道具绑定到输入字段上的onChange处理程序,该处理程序在您输入字段时触发。 So now you just need to ensure to pass the event object to onTyping handler.所以现在你只需要确保将event object 传递给onTyping处理程序。 This will call your handleChange with that event object and now you can make use of event.target.value and set it to your inputText .这将使用该event object 调用您的handleChange ,现在您可以使用event.target.value并将其设置为您的inputText

You can change你可以改变

 <input onChange={(e)=>
            props.onTyping(e)
          }

to

<input onChange={
            props.onTyping
          }

And it will work the same way.它会以同样的方式工作。 In second style, event object is passed implicitly.在第二种风格中, event object 被隐式传递。

If you look at what the onTyping function is, it's a reference to the handleChange function.如果您查看 onTyping function 是什么,它是对 handleChange function 的引用。 If you look at the definition of the handleChange function, you see that it takes an event argument.如果您查看 handleChange function 的定义,您会发现它接受了一个event参数。 In your line that didn't work:在您的行中不起作用:

<input onChange={()=>{ props.onTyping() }}

You weren't passing anything - there's nothing in the parenthesis - so this line in the handChange function:你没有传递任何东西——括号里什么都没有——所以这行在handChange function:

const newValue = event.target.value;

sets newValue to undefined because event wasn't passed in.将 newValue 设置为 undefined,因为未传入event

Your new line adds in e, or the event, as an argument, and hence it works.您的新行添加了 e 或事件作为参数,因此它可以工作。 The event is indeed generated by default, but you need to pass that event as an argument, otherwise the function won't get it.该事件确实是默认生成的,但是您需要将该事件作为参数传递,否则 function 将无法获取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM