2

我正在尝试使用 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第三个组件中第一个组件的值以插入数据库?

4

2 回答 2

2

您创建一个父容器。父容器保存状态、所有方法和事件处理程序。所有这些都与父级绑定。

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

https://codesandbox.io/s/q335wnjoyj

于 2018-06-06T06:46:19.123 回答
0

使用容器组件的概念。

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

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>

  }

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

于 2018-06-06T06:10:52.317 回答