我有一个名为FlexibleInput的无状态组件。
import React, { PropTypes } from 'react'
export default function FlexibleInput({
id,
label,
defaultValue,
type,
onChange,
}){
let fieldClass = `${id}-field`
return (
<fieldset className={fieldClass}>
<label htmlFor={id}>{label}</label>
<input
key={id}
id={id}
type={type}
defaultValue={defaultValue}
onChange={onChange}
/>
</fieldset>
)
}
FlexibleInput.propTypes = {
id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
defaultValue: PropTypes.string.isRequired,
type: PropTypes.string.isRequired, // accepts "text", "password" atm.
onChange: PropTypes.func.isRequired,
}
我在名为AddNote的表单中使用此FlexibleInput。
<form
className="note-list__add-note"
onSubmit={this.addNote}
ref={`${this.props.type}-addNoteForm`}
>
<FlexibleInput
id="note"
label="Awaiting changes..."
type="text"
defaultValue=""
onChange={(e) => this.setState({ content: e.target.value })}
/>
使用this.addNote函数提交后...我希望能够重置FlexibleInput输入值。
我设法做了一个丑陋的屁股黑客版......
this.refs[`${this.props.type}-addNoteForm`]
.childNodes[0].childNodes[1].value = ''
设法正确重置该值。这很容易发生变化,因为FlexibleInput的结构可能会发生变化?我不知道,希望不是。
但我的主要问题是,有没有办法可以做某种
this.refs[bla bla].find(#input)
左右?
在React / ReactDOM文档中不清楚哪个api可用于ref
。
谢谢!
答案 0 :(得分:3)
您可以创建Controlled component,使用组件状态设置输入值:
<form
className="note-list__add-note"
onSubmit={this.addNote}
ref={`${this.props.type}-addNoteForm`}
>
<FlexibleInput
id="note"
label="Awaiting changes..."
type="text"
defaultValue=""
value={this.state.content}
onChange={(e) => this.setState({ content: e.target.value })}
/>
然后您只需要在this.addNote
方法中重置内容值:
addNote() {
this.setState({ content: '' });
}
N.B。确保正确绑定addNote以确保正确引用this.setState。