React:我可以使用名为 "index" 的道具吗

React: can I use a prop named "index"

你可以从下面的代码块中看到 Description.js 我必须传递一个名为 "index"[= 的 prop 47=],因为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 和函数参数。它不必命名为索引。它们甚至不必相同。

你可以这样做,而且效果完全一样:

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} />


不,index 不是保留的 prop 名称。实际上,我所知道的唯一保留名称是 refkey