你可以从下面的代码块中看到,在 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/