使用reactjs中的多个组件插入数据

时间:2018-06-06 05:51:46

标签: reactjs react-component

我正在尝试使用reactjs中的多个组件在数据库中插入数据。在我的第一个组件中,我有一个如下所示的表单(此组件中没有Submit按钮)

render() {
return (
    <form>
        <input type="text" name="name" placeholder="Name"/>             
    </form>
);

}

在第二个组件中,我使用if else逻辑调用该组件。

在第三个组件中,我有如下的提交按钮

<Button 
   positive icon='checkmark' 
   labelPosition='right' 
   onClick={this.insertAddress}
   content='Save' 
/>

我的主要问题是使用state。如何在此有效使用state?如何捕获第三个组件中第一个组件的input值以插入数据库?

2 个答案:

答案 0 :(得分:1)

您创建父容器。父容器包含状态,所有方法和事件处理程序。所有这些都与父母有约束力。

然后将状态的方法和部分传递给子项。当他们的孩子使用它们时,他们将改变父母。我创建了一个简单的沙箱来演示。你不需要传递整个状态,只需要传递孩子所需的部分。

https://codesandbox.io/s/q335wnjoyj

答案 1 :(得分:0)

使用Container组件的概念。

创建一个容器组件,它将保存所有子组件的状态。在这里继续更新与数据相关的所有状态。并从此处调用保存功能。

class Parent extends React.Component{
     constructor(props){
        super(props);
        this.state={
           name:'',
           email:'',
           phone:''
        }
        this.handleFormChanges = this.handleFormChanges.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this);
        this.reactToSomeChange = this.reactToSomeChange.bind(this)
     }
      handleFormChanges(ev){
         // handle form and set appropriate state
      }
      handleFormChanges(ev){
         // react to change and set state
      }
      handleSubmit(){
         // update your data store db etc.
      }
      render(){
         return(
             <MyForm changes={this.handleFormChanges} />
             <IfElse changes={this.reactToSomeChange} />
             <Button submit={this.handleSubmit} />
         )
      }

}
// MyFrom component render function
   render() {
       return (
         <form>
           <input type="text" name="name" onChanges={this.props.changes} placeholder="Name"/>             
         </form>
        );
// Button component render function
 render(){
     <button onClick={this.props.submit}>SUBMIT<Button>

  }

子组件无需调用apis来保存数据。它应该从子组件中共享相同状态的单个父组件完成。