我在以下场景中使用DatePicker:
呈现使用DatePicker的表单 在componentDidMount上,获取表单的已保存信息(如果之前已保存) 将DatePicker的prop defaultValue从undefined设置为fetched值看起来很简单。 但是,由于DatePicker的行为是仅在第一次渲染时呈现defaultValue ,因此在获取值时显然为空(第二次渲染)。
我看到另外两个选项:
有一个受控组件 - 手动操作值(在获取时提供它,然后在onChange触发时更改它)
只有在无法获取(新表单)或获取数据并准备填充数据时,才会呈现DatePicker。
有关实现这一目标的最佳方法的任何想法?
I'm using DatePicker in the following scenario:
Render the form that used DatePicker on componentDidMount, fetch form's saved information (if it was saved previously) set DatePicker's prop defaultValue from undefined to the fetched valueSeems pretty simple. But, since DatePicker's behaviour is to render defaultValue only on the first render, it obviously is empty when the value is fetched (second render).
The other two options i see:
Have a controlled component - manipulate value manually (provide it when its fetched, and then change it when onChange fires)
Render DatePicker only if there's nothing to fetch (new form) or once the data has been fetched and ready to be populated.
Any thoughts on what the best approach would be to accomplish this?
最满意答案
而不是填充defaultDate prop,将value prop挂钩到您想要设置的任何value 。 使用这种方法,您还需要连接一个onChange处理程序。 它看起来像这样:
onChange(event, newValue) { this.setState({myDate: newValue}) }, render() { return ( ... <DatePicker value={this.state.myDate} onChange={this.onChangeHandler}> ... ) },或者,您可以使用React的LinkedStateMixin和DatePicker的valueLink prop来使用双向绑定功能。
Rather than populate the defaultDate prop, hook the value prop to whatever you want it set to. Using this approach, you'd also want to wire up an onChange handler. It would look something like this:
onChange(event, newValue) { this.setState({myDate: newValue}) }, render() { return ( ... <DatePicker value={this.state.myDate} onChange={this.onChangeHandler}> ... ) },Alternatively, you could use the two-way binding functionality using React's LinkedStateMixin and the DatePicker's valueLink prop.
更多推荐
发布评论