我正在尝试通过扩展material-ui文本字段来创建数字输入字段。为此,我需要验证输入值并停止传播无效值。如果输入有效,我希望顶部容器组件处理更改事件。但是,如果我为控件提供事件处理程序,它不会冒泡到容器组件。我怎样才能做到这一点?
这是我的代码 -
我的容器组件 -
class ItemsContainer extends Component {
handleItemChange(e)
{
console.log(e.target.value)
//dispatch further redux action
}
render()
{
const cartTable = () => <ItemTable lines = { this.props.Lines }
onItemChange = { this.handleItemChange.bind(this) } />
return({cartTable })
}
}
无状态表组件
const CartLineTable = ({
lines,
onItemChange = () => {},
}) => {
let rows = cartLines.map((cl, k) => <NumberField
id = { `${k}` }
color = 'primary'
defaultValue = { cl.value }
onChange = { (e) => onItemChange(e, k, cl) }/> )
return ( {rows })
}
数字输入的文本控制
import React, { Component } from 'react'
import TextField from 'material-ui/TextField'
class NumberFieldBehavior extends React.Component {
handleChange () {
console.log('change fired!', arguments)
//fire the parent components event handler ?
}
}
class NumberField extends NumberFieldBehavior {
render () {
return(
<TextField {...this.props} onChange = {this.handleChange.bind(this)}/>
)
}
}
export default NumberField
答案 0 :(得分:2)
您需要在onChange
组件中添加NumberField
道具,并在调用TextField
onChange
时调用传递给您的函数。< / p>
冒泡的一种可能实现:
class NumberField extends Component{
onTextFieldChange(){
//check condition for bubble up and then
this.props.onChange(anyArgsYouWantToPass);
}
render(){
return(
<TextField {...this.props} onChange={this.onTextFieldChange.bind(this)}/>
)
}
}
并像这样使用它:
<NumberField onChange={functionToCallOnValidChange}/>