在React.js中获取相同属性名的数组中input标签的值,可以通过以下步骤实现:
以下是一个示例代码:
import React, { Component } from 'react';
class InputArray extends Component {
constructor(props) {
super(props);
this.state = {
inputValues: Array(props.array.length).fill(''),
};
}
handleInputChange = (index, event) => {
const { value } = event.target;
this.setState((prevState) => {
const inputValues = [...prevState.inputValues];
inputValues[index] = value;
return { inputValues };
});
};
render() {
const { array } = this.props;
const { inputValues } = this.state;
return (
<div>
{array.map((item, index) => (
<input
key={index}
value={inputValues[index]}
onChange={(event) => this.handleInputChange(index, event)}
/>
))}
</div>
);
}
}
export default InputArray;
在上述示例中,InputArray组件接收一个名为array的属性,该属性是一个包含相同属性名的数组。组件内部使用state来存储每个input标签的值,通过onChange事件处理函数更新状态数组中对应位置的值。最后,通过访问状态数组inputValues来获取每个input标签的值。
这是一个简单的示例,你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云