代码之家  ›  专栏  ›  技术社区  ›  abu abu

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

  •  1
  • abu abu  · 技术社区  · 6 年前

    我试图使用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 . 我怎么用 状态 有效吗?我怎么能抓住 input 要插入数据库的第三个组件中的第一个组件的值?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Brian Tompsett - 汤莱恩 andrewwong97    6 年前

    创建父容器。父容器保存状态、所有方法和事件处理程序。所有这些都绑定到父对象。

    然后你把方法和部分状态传给孩子们。当孩子们使用它们时,他们会改变父母。我创建了一个简单的沙盒来演示。你不需要把整个州都传下去,只要孩子们需要的部分。

    https://codesandbox.io/s/q335wnjoyj

        2
  •  0
  •   hannad rehman    6 年前

    使用容器组件的概念。

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

    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来保存数据。应该从共享子组件中相同状态的单个父组件执行此操作。