【发布时间】:2024-05-29 17:45:02
【问题描述】:
我正在将 Reflux 用于论坛,我正在尝试制作它,以便用户可以选择要写入的类别,然后填写模板。
为此,我在下拉菜单中为onChange 设置了一个setCategory 函数,它设置状态并因此重新呈现表单。
<Categories onChange={this.setCategory} value={this.state.category} />
// where setCategory is a function which sets the state
// to the selected category.
表格是这样写的:
<textarea id='content' defaultValue={this.placeholder()}></textarea>
其中占位符是一个函数,它返回应该插入到文本区域的数据:
placeholder: function() {
if (this.state.category == 'ban-appeals'){
return ('text here...');
} // ...
}
但是,我遇到的问题是:重新渲染 textarea 时,框内的文本不会从最初开始的文本更改。我希望它清空该框并根据类别设置文本,但该框不会从最初提供给它的“占位符”文本更改。
那么,有没有办法在更改页面状态时更新 textarea 的 defaultValue?。
我最好的猜测是 defaultValue 仅在首次创建 textarea 框时才考虑 - 因此,当我们更改状态时,框可能认为它已经“初始化”,因此不会更新值,因为它只是在初始化盒子时才设置的默认值?
我尝试将defaultValue 属性更改为纯value(如<textarea value={this.placeholder()}>...),但这给了我来自javascript 的错误:
Warning: Failed propType: You provided a `value` prop to a form field without an `onChange` handler.
This will render a read-only field. If the field should be mutable use `defaultValue`.
Otherwise, set either `onChange` or `readOnly`. Check the render method of `exports`.
此外,当我选择带有占位符文本的类别时,该框不可编辑。
我还尝试将{this.placeholder()} 调用放在textarea 标记中(如<textarea>{this.placeholder()}</textarea>),但这导致更改类别时textarea 没有任何变化。
我知道表单肯定会再次呈现,因为我可以在render 函数的顶部放置一个console.log 调用,该函数定义了textarea,并在每个更改时打印类别。
那么,当类别改变时,我可以做些什么来改变框的值,同时仍然让用户编辑它?
谢谢。
【问题讨论】:
标签: javascript html refluxjs