簡體   English   中英

反應:我可以使用名為“索引”的道具嗎

[英]React: can I use a prop named “index”

您可以從下面的代碼塊中看到,在Description.js內部,我必須傳遞一個名為“ index”道具 ,因為handleChange是必須使用兩個參數handleChange(newValue,index)調用的函數。

handleChange函數更新狀態,在這種情況下,該狀態為長度為3(每個輸入一個值)的數組。

而且由於index是由Description.js組件創建的,因此我不得不將其作為道具傳遞給他人。

它按預期工作。

這是不好的做法嗎? index是某種保留字(React,Javascript或HTML)嗎?

有更好的方法嗎?


App.js

import React, { useState, useCallback } from "react";
import ReactDOM from "react-dom";
import Description from "./Description";

function App() {
  console.log("Rendering App...");
  const [inputValues, setInputValues] = useState(["", "", ""]);

  const handleChange = useCallback((newValue, index) => {
    setInputValues(prevState => {
      const aux = Array.from(prevState);
      aux[index] = newValue;
      return aux;
    });
  }, []);

  return <Description values={inputValues} handleChange={handleChange} />;
}

Description.js

import React from "react";
import TextInput from "./TextInput";

function Description(props) {
  console.log("Rendering Description...");
  const inputItems = props.values.map((item, index) => (
    <div key={index}>
      <div>Input {index + 1}</div>
      <TextInput value={item} handleChange={props.handleChange} index={index} />
    </div>
  ));

  return <React.Fragment>{inputItems}</React.Fragment>;
}

TextInput.js

import React from "react";

const TextInput = React.memo(function TextInput(props) {
  console.log("Rendering TextInput..." + props.index);
  return (
    <input
      type="text"
      value={props.value}
      onChange={event => props.handleChange(event.target.value, props.index)}
    />
  );
});

您所做的事情沒有任何問題,但是您可以根據需要調用prop和function參數。 它不必命名為index。 他們甚至不必相同。

您可以這樣做,它的工作原理完全相同:

const handleChange = useCallback((newValue, bananas) => {
    setInputValues(prevState => {
      const aux = Array.from(prevState);
      aux[bananas] = newValue;
      return aux;
    });
  }, []);

與此相同:

const TextInput = React.memo(function TextInput(props) {
  console.log("Rendering TextInput..." + props.wookie);
  return (
    <input
      type="text"
      value={props.value}
      onChange={event => props.handleChange(event.target.value, props.wookie)}
    />
  );
});

// and then...
<TextInput value={item} handleChange={props.handleChange} wookie={index} />


不,索引不是保留的道具名稱。 實際上,我所知道的唯一保留名稱是refkey

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM