在流星中react不工作的defaultValue
defaultValue of react not working in meteor
我正在努力解决这个问题,我不知道为什么不起作用
<input type="text" id="first_name" name="first_name" className="form-control" defaultValue={this.props.user.first_name} required/>
但这对有效
<input type="text" id="first_name" name="first_name" className="form-control" value={this.props.user.first_name} required/>
区别是value
和defaultValue
,如果我使用值,字段将变为只读,并且使用defaultValue不会打印任何内容。
我正在用流星反应。在return
语句之前,我曾尝试在render方法中记录this.props.user
,它会打印对象。
当您将this.props.user.first_name
分配给value
属性时,并不是输入字段变为只读,而是您永远不会处理该值更改时发生的情况。React只是用每次直接分配给它的值重新渲染它。
如果您希望使字段可编辑+具有默认用户名值,则可能需要维护并了解输入的状态。
例如:
// Initialize some component state in either your constructor or getInitialState function
constructor(props){
super(props);
this.state = {userInput: this.props.user.first_name};
}
// Have a function that updates state when your input changes
onInputChange(event) {
this.setState({ userInput: event.target.value });
}
// Then set the value equal to your userInput state and add an onChange
// prop to the input tag in your render method.
render() {
return (
...
<input
type="text"
id="first_name"
name="first_name"
className="form-control"
value={this.state.userInput}
onChange={this.onInputChange.bind(this)} />
)
}
然后,字段的值初始化为通过this.props.user.first_name
提供的值,同时保持可编辑状态。
编辑:
正如评论中所指出的,虽然这是有效的,但这实际上是React中的一种反模式。因为子组件的初始状态只调用一次,所以从父组件更改为this.props.user.first_name
的prop值不会导致子组件的状态发生任何更改。如果用例是明确地设置一个初始值,而您不希望或期望在组件生命周期中更改该初始值(尽管即使在那时,这也不是一个好的模式),那么这是可以的,但如果您确实期望初始值是可变的,那么您有两种选择。
选项一:将状态带入父组件,它可能属于该组件。然后,子组件应该接收并呈现按其方式发送的任何道具。对初始值的更改在父组件状态下处理,道具被视为不可变的,并且一切保持同步。
选项二:如果出于任何原因,您都需要从道具中确定状态,并且您也希望这些道具发生变化,那么您可以使用componentWillReceiveProps(nextProps)
生命周期方法来保持一切同步。这将允许您对照nextProps
检查this.props
,并在必要时进行任何状态更改:
componentWillReceiveProps(nextProps) {
if(nextProps.user.first_name !== this.props.user.first_name){
this.setState({
userInput: nextProps.user.first_name
});
}
}
以下是DOCS的链接以供进一步参考。
- Javascript:selenium Web驱动程序isDisplayed()不工作
- jQuery UI自动完成突然停止工作
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JavaScript打印功能使日历停止工作
- Javascript.getHours()工作不正常
- 为什么这在IE中的工作方式与在Firefox中不同
- 视频HTML没有'无法在Internet Explorer 11上工作
- 扩展移相器按钮类不工作
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- 正在尝试使用if和else添加类,但无法正常工作
- Jquery FadeIn FadeOut 只工作一次
- Foreach无法在Typescript中工作
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- JS可以在Chrome中工作,但不能在Firefox中工作
- ajaxToolkit PopupControlExtender不工作.过时的
- HTML标记在脚本标记中工作
- 在流星中react不工作的defaultValue