对传递给二级孩子的道具做出反应

时间:2020-07-23 07:54:16

标签: javascript reactjs children prop

我在React编码时遇到了传递道具的问题。是的,我之前已经看过这个问题,但是这次是第二级的子组件,情况有些奇怪。我的代码(一路上的评论):

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>
    );
  }
}

输出:

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

有人可以解释为什么我不能连续两次通过道具吗?实际上,这些值在UpdateModal中时仍然有效,但后来以某种方式消失了。

谢谢。

2 个答案:

答案 0 :(得分:1)

您应将事件对象传递给处理程序:

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>
    );
  }
}

答案 1 :(得分:0)

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>