【发布时间】:2018-09-28 11:38:37
【问题描述】:
我正在尝试在 Material-UI 中的 TextField 上使用 React 的“ref”属性访问输入数据。似乎没有一种简单的方法可以通过“inputRef”或“inputProps”来做到这一点。
下面的示例在第 26 行显示了 inputProps 的使用。将 TextField 的名称分配给 'ref' 属性似乎不会产生有效的对象。
使用“inputRef”,根据Material-ui 文档强制使用函数,尝试将字段数据作为属性传递也不起作用。例如:(txt => this.name = txt)
有人找到解决办法了吗?
class MediaForm extends Component {
constructor (props) {
super(props)
this.state = {}
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit (e) {
const { title, colour } = this.refs
e.preventDefault()
window.alert(`New colour: ${title.value} ${colour.value}`)
}
render () {
const { classes } = this.props
return (
<form className={classes.root}
onSubmit={this.handleSubmit}>
<div className={classes.field}>
<TextField
name='title'
type='text'
label='Title'
placeholder='Movie title...'
autoFocus
inputProps={{ref: this.name}}
required />
</div>
<div className={classes.field}>
<Tooltip title='Add a colour the reflects the mood of the film'>
<TextField
name='colour'
type='color'
label='Mood'
inputProps={{ref: this.name}}
required />
</Tooltip>
</div>
<Button
variant='raised'
color='primary'
className={classes.button}>
ADD
</Button>
</form>
)
}
}
MediaForm.propTypes = {
classes: PropTypes.object.isRequired
}
export default withRoot(withStyles(styles)(MediaForm))
【问题讨论】:
标签: javascript reactjs material-ui