加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

表格 – React – 预填充表格

发布时间:2020-12-15 20:31:32 所属栏目:百科 来源:网络整理
导读:我需要预先填充表单,以便用户可以编辑他们之前创建的博客.我正在寻找在React中做到这一点的最佳实践方法.我目前通过props将值传递给组件,然后将state属性设置为等于props属性,但我已经读过这是一个反模式.我理解’事实的来源’.但是有什么更好的方法呢?我现
我需要预先填充表单,以便用户可以编辑他们之前创建的博客.我正在寻找在React中做到这一点的最佳实践方法.我目前通过props将值传递给组件,然后将state属性设置为等于props属性,但我已经读过这是一个反模式.我理解’事实的来源’.但是有什么更好的方法呢?我现在不想使用redux-form.下面是我的标题组件,下面是我从父母那里调用它的方式.这一切都有效,但有没有更好的方法,以避免将州属性设置为道具属性?

import React,{ Component,PropTypes} from 'react';

export default class DocumentTitle extends Component{
  constructor(props) {
      super(props);
      this.state = {inputVal:this.props.publication.document_title}
      this.handleChange = this.handleChange.bind(this)
  }

  handleChange(event) {
    this.setState({inputVal: event.target.value});
  }

  componentWillReceiveProps(nextProps){
    this.setState({inputVal: nextProps.publication.document_title})
  }

  render (){
    return (
      <div >
        <label>Title</label>
        <div>
          <input onChange={this.handleChange} id="doc_title" type="text" value={this.state.inputVal}/>
        </div>
      </div>
    )    
  }
}

来自父母的电话:

<DocumentTitle publication={this.props.publication} />

解决方法

如果在父级中维护发布,则不需要维护状态,除非有其他原因:验证一个.

输入可以是不受控制的组件.输入的onBlur可用于更新父级.

<input 
  onBlur={e => this.props.onTitleChange(e.target.value)}
  id="doc_title" 
  type="text" 
  defaultValue={this.props.publication.document_title} />

父组件应更新发布状态.

<DocumentTitle 
  publication={this.state.publication} 
  onTitleChange={this.handleTitleChange} />

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读