一个组件中的表单由其他组件提交

时间:2018-05-05 13:55:33

标签: javascript reactjs react-redux

我在CreateCandidate中有两个组件CreateCandidate和技术,它需要从技术组件接收的技术,所以当我将技术传递给CreateCandidate时,CreateCandidate中的表单将在此处提交是我的代码

CreateCandidate: -

class CreateCandidate extends Component {
    submit(e) {
        e.preventDefault();
        var data = new FormData(e.target)
        fetch('/candidate', {
            method: 'POST',
            body: data,
        }).then(res => res.json())
            .then(res => console.log(res))
            .catch(res => console.log(res))
    }
    getTech(e, data) {
        e.preventDefault();
        this.state.form['technologies'] = data;
        this.setState({ form: this.state.form });
    }
    render() {
                ...
                        <form className="" onSubmit={this.submit.bind(this)}>

                                        <Technologies getTech={this.getTech.bind(this)} />

                                <button type="submit" id="button" className="btn btn-primary btn-lg btn-block login-button" >Create</button>

                        </form>               
    }
}

技术组件:

class Technologies extends React.Component {
    constructor() {
      super();
      this.state = {
        technologies: [''],
      };
    }


    handleSubmit(evt){
     this.props.getTech(this.state.technologies);
    }            
    render() {    
      return (
        <div>
          {this.state.technologies.map((technology, idx) => (
              <input
                type="text"
                placeholder={`Technology #${idx + 1}`}
                value={technology[idx]}
                onChange={this.handleTechnologyChange(idx)}
              />
              <button type="button" onClick={this.handleRemoveTechnology(idx)} className="small">-</button>
          ))}
          <button type="button" onClick={this.handleAddTechnology} className="small">Add Technology</button>
          <button>Done</button>
          </div>
      )
    }
  }
  export default Technologies

而且当我在状态中更改数组时,它也会在UI组件中反映出来。

1 个答案:

答案 0 :(得分:2)

尝试将每个按钮的类型设置为button,不应触发表单提交:

render() {    
  return (
    <div>
      {this.state.technologies.map((technology, idx) => (
        <div className="shareholder">
          <input
            type="text"
            placeholder={`Technology #${idx + 1}`}
            value={technology[idx]}
            onChange={this.handleTechnologyChange(idx)}
          />
          <button type="button" onClick={this.handleRemoveTechnology(idx)} className="small">-</button>
        </div>
      ))}
      <button type="button" onClick={this.handleAddTechnology} className="small">Add Technology</button>
      <button type="button">Done</button>
      </div>
  )
}

我认为有些标签如:

<label for="technologies" className="cols-sm-2 control-label">Technologies</label>

可能会触发提交。