我试图学习如何实现React表单(ES6语法)并将每个字段的onChange事件传递给负责更新状态的控制器父组件。这适用于标准的html元素,但是我正在为日期字段尝试预先固定的Datepicker(https://www.npmjs.com/package/react-bootstrap-date-picker),并且不能以相同的方式将事件传递回父级。有没有一种简单的方法来解决这个问题?
控制器组件
class Parent extends React.Component {
constructor (props) {
super(props);
this.state = {job: ''}
}
setJobState(event) {
var field = event.target.name;
var value = event.target.value;
this.state.job[field] = value;
this.setState({job: this.state.job});
}
render () {
return <Child onChange={this.setJobState.bind(this)} />
}
}
子组件
class Child extends React.Component {
constructor (props) {
super(props);
}
render () {
<form>
<input type="text" name="jobNumber" onChange={this.props.onChange} />
<DatePicker name="dateCmmenced" onChange={this.props.onChange} />
</form>
}
}
答案 0 :(得分:28)
DatePicker
的{{1}}处理程序未使用标准浏览器change
事件调用,但value
和formattedValue
作为参数。我建议在onChange
组件中注册不同的Child
处理程序,以便转换相应的输入字段的事件:
控制器组件
class Parent extends React.Component {
constructor (props) {
super(props);
this.state = {}
}
onChange(field, value) {
// parent class change handler is always called with field name and value
this.setState({[field]: value});
}
render () {
return <Child onChange={this.onChange.bind(this)} />
}
}
子组件
class Child extends React.Component {
constructor (props) {
super(props);
}
onFieldChange(event) {
// for a regular input field, read field name and value from the event
const fieldName = event.target.name;
const fieldValue = event.target.value;
this.props.onChange(fieldName, fieldValue);
}
onDateChange(dateValue) {
// for a date field, the value is passed into the change handler
this.props.onChange('dateCommenced', dateValue);
}
render () {
return <form>
<input type="text" name="jobNumber" onChange={this.onFieldChange.bind(this)} />
<DatePicker onChange={this.onDateChange.bind(this)} />
</form>
}
}
答案 1 :(得分:0)
import React from 'react'
export default {
[formData, setFormData] = React.useState({
name: '',
number: '',
email: '',
address: '',
zip: ''
})
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value })
}
return (
<div>
<input type='text' name='name' onChange={handleChange} />
<input type='text' name='number' onChange={handleChange} />
<input type='email' name='email' onChange={handleChange} />
<textarea name='address' onChange={handleChange}></textarea>
<input type='text' name='zip' onChange={handleChange} />
</div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>