简体   繁体   English

React 将 props 传递给二级子级

[英]React Passing Props to Second-level Children

I faced the problem of passing props while coding in React.我在 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.事实上,这些值在 UpdateModal 中时仍然有效,但之后不知何故消失了。

Thanks in advance.提前致谢。

You should pass in the event object to your handlers:您应该将事件 object 传递给您的处理程序:

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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