ReactJS使用Props数组改变表格输入

时间:2017-10-02 18:27:11

标签: javascript reactjs

试图弄清楚如何为表单动态处理不同数量的道具数据。我的谷歌搜索没有任何结果。我正在根据相关用户拥有的号码狗收集约会数量的数据。所以道具看起来像这样:

this.props: {
  user: {
    id: 11
    name: "Steve",
    age: 32
  }
  dogs: [{
    id: 18,
    name: "Rover"
  },{
    id: 42,
    name: "Snugglemittens"
  }]
}

每个用户都有不同数量的狗。我的父元素视图如下所示:

render(){
    <form onSubmit={this._handleSubmit.bind(this)}>
      {this.props.dogs.map((dogge)=>{
        return(<MsgView dog={dogge} key={dogge.id} />;)
      }}
      <button type="submit">Submit</button>
    </form>
}

然后在每个Message视图中,我想收集关于每只狗的两个复选框:

render(){
  <div className="form-group" data-toggle="buttons">
    <label><input type="checkbox" autoComplete="off"/> XYZ </label>
  </div>
  <div className="form-group" data-toggle="buttons">
    <label><input type="checkbox" autoComplete="off"/> ABC </label>
  </div>
}

我不知道如何使用ajax将填充的数据传回我的后端。我最初的想法是使用状态来收集信息并立即将其发回。我很确定React可以通过我可以使用的道具传递函数,但我找不到一个好的例子。

1 个答案:

答案 0 :(得分:1)

这是我认为可行的。您可以在加载视图时填充this.state

// or in a lifecycle method componentWillMount or componentDidMount instead
// and do in constructor, this.state = { dogs: [] }
// sorry, this is kind of hard to do abstractly

constructor(props) {
  super(props)
  // on pageload, set initial state to the doggo array
  this.state = {
    dogs: this.props.dogs
  }
}

// alternate solution potential:
componentDidMount() {
  this.setState({ dogs: this.props.dogs })
}

_handleSubmit() {
  console.log('FIELDS:', this.state.dogs)
  // now we're in business if you see your data
}

render(){
    if (this.state.dogs.length === 0) return <div>No dogs yet, loading spinner</div>
    return (
      <form onSubmit={() => this._handleSubmit()}>
        {this.state.dogs.map((dogge)=> {
          return(
            <MsgView
              dog={dogge}
              key={dogge.id}
              {/* on change, update state of field */}
              onChange={(e) => this.setState({
                {/* ie: dogs[0], dogs[45]
                    you might have to use ES6 .find() or something
                    you guys/girls see where I'm going with this
                    basically update the array or make better data structure.
                    I like the idea of this.state.dogs[doggo]
                    (so dogs is an object with dynamic keys)
                    then you can just update the value of that key with setState */}
                dogs[this.state.dogs.indexOf(dogge)]: e.target.value
              })}
            />
          )}
        }
        <button type="submit">Submit</button>
      </form>
    )
  }

我不记得它是e.target.value,但是你应该看看我得到了什么。

  1. 您将狗从道具转移到组件状态
  2. 让状态保持最新
  3. 提交后阅读