我正在尝试在React中创建一个表单组件,类似于Formik,但更简单。
我考虑的方式是给所有子元素添加一个onChange
处理程序。我用children.map()
实现了这一点。它可以运行,但是会出现key警告。
Warning: Each child in a list should have a unique "key" prop.
我知道没有办法去抑制这个问题,也许有更好的方法来创建这个表单组件?
此外,当 <input>
不是直接子元素时,应该如何处理?
编辑:我知道如何避免这个问题,我主要想知道最佳的解决方法,包括嵌套输入框的情况。
这是我想要使用它的方式:
<Form>
<label htmlFor="owner">Owner</label>
<input
type="text"
name="owner"
id="owner"
/>
<label htmlFor="description">Description</label>
<input
type="text"
name="description"
id="description"
/>
<input
type="submit"
value="Submit"
/>
</Form>
这是我的代码:
import React from 'react';
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {}
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value =
target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
console.log(`${name} : ${value}`)
this.setState({
[name]: value
});
}
render() {
return (
<form>
{this.props.children.map((child) => {
if (child.type === "input") {
return (
<input
onChange={this.handleInputChange}
{...child.props}
/>
)
}
})}
</form>
)
}
}
export default Form;