javascript - react : can I use a prop named "index"

标签 javascript reactjs react-hooks

你可以从下面的代码块中看到,在 Description.js 中,我必须传递一个名为“index”的 prop,因为 handleChange 是一个必须使用两个参数调用的函数 handleChange(newValue,index)

handleChange 函数更新状态,在本例中,它是一个长度为 3 的数组(每个输入一个值)。

因为 index 是由 Description.js 组件创建的,所以我不得不将它作为 props 传递下去。

它按预期工作。

问题

这是一种不好的做法吗? 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} />


关于javascript - react : can I use a prop named "index",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56328860/

相关文章:

javascript,Array.prototype.map()。索引未定义

reactjs - React Hooks,如何实现useHideOnScroll hook?

javascript - 获取页面 token 以将我的应用程序订阅到用户页面

javascript - 属性 'submitAction' 在类型 '{}' 中缺失,但在类型中需要

javascript - 从 gulp 任务运行 Node js 脚本

node.js - 将 React Starter Kit(由 Kriasoft 提供)部署到 Heroku

javascript - 如何在 React Hook 中创建一个新的 JSON 对象?

reactjs - 使用 useEffect 获取数据时避免旧数据

javascript - 如何使用 jQuery 删除跨度数值的 25%?

javascript - Gatsby 热重载不会在 Hello World 入门项目中重载