在React中更新childs prop组件后更改父状态?

时间:2019-10-03 05:01:02

标签: javascript reactjs

我是新来的人。我在分配给状态的应用程序组件中有一个访存调用。我将该状态作为道具以及将功能发布到子组件的函数传递。在我的子组件中,您可以发布/删除以更改道具,目前还没有push()来添加新的联系人/道具。我更改孩子的道具后,是否可以更改父组件的状态?有更好的方法吗?

我正在尝试执行发布操作,以更新应用程序上的状态。

应用代码

class App extends Component {

  constructor() {
    super();
    this.state= {
      contacts:[], 
      addModalShow: false,
      modalIsOpen: false
    }
  }

  componentDidMount() {
      var request = new Request('http://localhost:3000/', {
          method: "GET",
      });
      fetch(request)
          .then((res) => {
              res.json()
                  .then((data) => {
                      this.setState({
                        contacts: data.rows
                      })
                  })
          })
  }

  toggleModal() {
    this.setState({
        modalIsOpen: ! this.state.modalIsOpen
    })
}

  addContact(event) {
        this.toggleModal()
        event.preventDefault();
        let contactData = {
            first: this.refs.first.value,
            last: this.refs.last.value,
            phone: this.refs.phone.value,
            email: this.refs.email.value,
        };
        var request = new Request('http://localhost:3000/add', {
            method: "POST",
            headers: new Headers({ 'Content-Type': 'application/json' }),
            body: JSON.stringify(contactData)
        });

        console.log(this.state)

        fetch(request)
            .then((res) => {
                res.json()
                    .then((data) => {
                    })
            })
            .catch((err) => {
                console.log(err)
            })
    }

  render() {

    return (
      <Container>
        {console.log(this.state)}
        <AddContact  addContact={this.addContact} contacts={this.state.contacts} />
        <ContactList contacts={this.state.contacts} />
        <Contacts contacts={this.state.contacts}/>

      </Container>
    );
  }
}

export default App;

子组件

class AddContact extends Component {
    constructor(props) {
        super(props);
        this.state = {
            contacts: [],
            modalIsOpen: false,
        }
    }

    toggleModal() {
        this.setState({
            modalIsOpen: ! this.state.modalIsOpen
        })
    }


    render() {
        return(
            <Container>
                <div className='header'>
                    <h1>
                        My Contacts
                        <button className='addContactButton' onClick={this.toggleModal.bind(this)}>+</button>
                    </h1>
                    <hr />
                </div>
                <Modal isOpen={this.state.modalIsOpen}>
                <form ref='addContact' >
                    <div className='addContactHeader'>
                        <button className='saveButton' onClick={this.props.addContact.bind(this)}>Save</button>
                        <button className='cancelButton' onClick={this.toggleModal.bind(this)}>Cancel</button>
                    </div>
                    <div id="circle">
                        Add Photo
                    </div>
                    <div className="inputFields">
                        <div className='nameInputs'> 
                            <input type='text' ref='first' placeholder='first name' />
                            <input type='text' ref='last' placeholder='last name' />
                        </div>
                        <div className='extraInputs' >
                            <input type='text' ref='phone' placeholder='phone' />
                            <input type='text' ref='email' placeholder='email' />
                        </div>
                    </div>
                </form>

                </Modal>
          </Container>
        )
    }  
}

感谢您的时间

2 个答案:

答案 0 :(得分:1)

您可以使用回调函数来更新父组件上的状态(另一种方法是使用Redux更新Store中的值,这样两个组件都可以访问该值),这是您可以使用的方法使用回调(带有一点ES6重构):

应用程序:

class App extends Component {
  state= {
    contacts:[], 
    addModalShow: false,
    modalIsOpen: false
  }

  componentDidMount() {
    let request = new Request('http://localhost:3000/', {
        method: "GET",
    });

    fetch(request)
        .then((res) => {
            res.json()
                .then((data) => { this.setState({ contacts: data.rows }) })
        })
   }

  toggleModal = () => {
    this.setState({ modalIsOpen: ! this.state.modalIsOpen })
  };

  addContact = event => {
        this.toggleModal()
        event.preventDefault();
        let contactData = {
            first: this.refs.first.value,
            last: this.refs.last.value,
            phone: this.refs.phone.value,
            email: this.refs.email.value,
        };
        let request = new Request('http://localhost:3000/add', {
            method: "POST",
            headers: new Headers({ 'Content-Type': 'application/json' }),
            body: JSON.stringify(contactData)
        });

        fetch(request)
            .then((res) => {
                res.json()
                    .then((data) => {
                    })
            })
            .catch((err) => {
                console.log(err)
            })
    };

  changeContacts = (newData) => {
    this.setState({ contacts: newData });
  };

  render() {
    const { contacts } = this.state; 

    return (
      <Container>
        <AddContact
          addContact={this.addContact}
          contacts={contacts}
          onChildAction={this.changeContacts}
        />
        <ContactList contacts={contacts} />
        <Contacts contacts={contacts}/>
      </Container>
    );
  }
}

export default App;

添加联系人:

class AddContact extends Component {
    state = {
      contacts: [],
      modalIsOpen: false,
    }

    toggleModal = () => {
        this.setState({ modalIsOpen: ! this.state.modalIsOpen })
    };

    // Here is where you'll send the info for the change of the prop
    changeProp = e => {
      const { onChildAction } = this.props;
      onChildAction('Your new state/prop value here')
      addContact(e);
    };

    render() {
    const { changeProp } = this.props;
    const { modalIsOpen } = this.state;

    return(
      <Container>
        <div className='header'>
          <h1>My Contacts
            <button className='addContactButton' onClick={this.toggleModal}>+</button>
          </h1>
          <hr />
        </div>
        <Modal isOpen={modalIsOpen}>
          <form ref='addContact' >
            <div className='addContactHeader'>
              <button className='saveButton' onClick={changeProp}>Save</button>
              <button className='cancelButton' onClick={this.toggleModal}>Cancel</button>
             </div>
             <div id="circle">Add Photo</div>
             <div className="inputFields">
               <div className='nameInputs'> 
                 <input type='text' ref='first' placeholder='first name' />
                 <input type='text' ref='last' placeholder='last name' />
               </div>
               <div className='extraInputs' >
                 <input type='text' ref='phone' placeholder='phone' />
                 <input type='text' ref='email' placeholder='email' />
               </div>
             </div>
           </form>
         </Modal>
      </Container>
    )
  }  
}

您需要做的最后一件事是确定要在哪里更改状态/属性。希望这会有所帮助。

答案 1 :(得分:0)

要处理来自孩子的父母,您需要将{ "newUsersJson": "[]", "existingUsersJson": "[\"55b98726-c6f5-48d2-976b-xxxxxx\"]", "groupsToJoinJson": "[\"7283653f-54b2-4ebf-86c3-xxxxxxx\"]", "aadGroupsJson": "[]" } 绑定到孩子

父组件

<FORM Method="POST" Name="f"
      Action="search.php">

<TABLE BORDER="1" CELLSPACING="0" CELLPADDING="8" RULES="groups"
       BORDERCOLOR="#DDD6E4" BGCOLOR="#F5F5F5">

<TBODY>
<TR><TD>
<SELECT NAME="srch1v" ID="SEL1" OnChange="SelProc(this, 'OPT1', 'SRCH1', 0)">
<OPTION VALUE="">Data Type
<OPTION VALUE="S" SELECTED>Surname
<OPTION VALUE="G">GivenName
<OPTION VALUE="T">Town
<OPTION VALUE="X">Any Field
</SELECT>

<SELECT NAME="srch1t" ID="OPT1">
<OPTION VALUE="">Search Type
<OPTION VALUE="Q" SELECTED>Phonetically Like
<OPTION VALUE="D">Sounds Like
<OPTION VALUE="S">Starts with
<OPTION VALUE="E">is Exactly
</SELECT>

<INPUT name="srch1" ID="SRCH1" size="25" maxlength="25">
</TD></TR>
<TR><TD>

<SELECT NAME="srch2v" ID="SEL2" 

        OnChange="SelProc(this, 'OPT2', 'SRCH2', 0)">
<OPTION VALUE="">Data Type
<OPTION VALUE="S">Surname
<OPTION VALUE="G" SELECTED>GivenName
<OPTION VALUE="T">Town
<OPTION VALUE="X">Any Field
</SELECT>

<SELECT NAME="srch2t" ID="OPT2">
<OPTION VALUE="">Search Type
<OPTION VALUE="Q"  SELECTED>Phonetically Like
<OPTION VALUE="D">Sounds Like
<OPTION VALUE="S">Starts with
<OPTION VALUE="E">is Exactly
</SELECT>
<INPUT name="srch2" ID="SRCH2" size="25" maxlength="25">
</TD></TR>
</TBODY>

在AddContact组件内部:

您可以调用 this.props.addContact()执行父函数