1
我有一个无状态组件,名为FlexibleInput。重置ReactDOM中的值参考儿童(最佳实践?)
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
。
谢谢!
<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: '' });
}
当我以前试过这个,它不会允许我编辑“值”,但现在(几个月后)我正在这样做,它按预期工作。不知道是否在我的最终或错误上存在错误,但使用受控组件似乎是一种方法!谢谢:) –
你还记得你使用的是什么版本的React吗?无论哪种方式很高兴我可以帮助! – Pineda
不幸的不是。我相信这可能是因为我没有正确地约束状态,并且仍在使用道具,所以没有显示“实时编辑”或更改为输入值。 –