简体   繁体   中英

React Passing Props to Second-level Children

I faced the problem of passing props while coding in React. Yes, I have seen this issue before, but this time it's a second level-children component and things are a bit weird. My code (comments along the way):

class EditForm extends React.Component {
  handleSubmit = (event, idx) => {
    event => event.preventDefault();
      postData('/', {idx: idx})
    .then(data => {if (data.success) {window.location = '/';}});
    console.log(idx);          // results printed from here
  }

  render() {
    return (
      <Form
        onFinish={() => this.handleSubmit(idx)}                 // output 1
        onFinish={() => this.handleSubmit(this.props.idx)}      // output 2
      >
      </Form>
    );
  }
}

class UpdateModal extends React.Component {
  render() {
    return (
      <Modal>
        <EditForm idx={ this.props.idx } />             // value is still not undefined        
      </Modal>
    );
  }
}

Outputs:

// 1
useForm.js:766 ReferenceError: idx is not defined
// 2
undefined

Can anyone please explain why I can't pass the props two times in a row? As a matter of fact, the values are still valid when they are in UpdateModal but is gone somehow afterward.

Thanks in advance.

You should pass in the event object to your handlers:

class EditForm extends React.Component {
  handleSubmit = (event, idx) => {
    event => event.preventDefault();
      postData('/', {idx: idx})
    .then(data => {if (data.success) {window.location = '/';}});
    console.log(idx);          // results printed from here
  }

  render() {
    return (
      <Form
        onFinish={(event) => this.handleSubmit(event, idx)}                 // output 1
        onFinish={(event) => this.handleSubmit(event, this.props.idx)}      // output 2
      >
      </Form>
    );
  }
}

class UpdateModal extends React.Component {
  render() {
    return (
      <Modal>
        <EditForm idx={ this.props.idx } />             // value is still not undefined        
      </Modal>
    );
  }
}
class EditForm extends React.Component { constructor(props) { super(props); } // ... } class UpdateModal extends React.Component { constructor(props) { super(props); } // ... } // <EditForm idx={this.state.idx}></EditForm> // <UpdateModal idx={this.state.idx}></UpdateModal>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM