React子组件的onChange事件更新状态 [英] onChange event for React child component to update state
问题描述
我正在尝试学习如何实现React表单(ES6语法)并将每个字段的onChange事件传递给负责更新状态的控制器父组件。这适用于标准的html元素,但我正在尝试预先制作的Datepicker( https ://www.npmjs.com/package/react-bootstrap-date-picker )对于日期字段,并且不能以相同的方式将事件简单地传递回父级。有没有一种简单的方法来解决这个问题?
I'm trying to learn how to implement a React form (ES6 syntax) and pass the onChange events for each field up to a controller parent component which is responsible for updating the state. This works fine for standard html elements, however I am trying a pre-canned Datepicker (https://www.npmjs.com/package/react-bootstrap-date-picker) for a date field and can't readily pass the event back up to the parent in the same way. Is there a simple way to address this?
控制器组件
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>
}
}
推荐答案
使用标准浏览器调用 onChange
DatePicker
的处理程序更改
事件,但值
和 formattedValue
作为参数。我建议在 Child
组件中注册不同的 onChange
处理程序,以转换相应的输入字段的事件:
The onChange
handler for the DatePicker
is not called with a standard browser change
event, but with value
and formattedValue
as arguments. I would recommend to register different onChange
handlers in your Child
component that transform the respective input field's event:
控制器组件
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>
}
}
这篇关于React子组件的onChange事件更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!