【问题标题】:React Passing Props to Second-level ChildrenReact 将 props 传递给二级子级
【发布时间】:2020-07-23 07:54:16
【问题描述】:

我在使用 React 编码时遇到了传递 props 的问题。是的,我以前见过这个问题,但这次是二级子组件,事情有点奇怪。我的代码(一路上的cmets):

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 中时仍然有效,但之后不知何故消失了。

提前致谢。

【问题讨论】:

    标签: javascript reactjs children prop


    【解决方案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>
        );
      }
    }
    

    【讨论】:

      【解决方案2】:
      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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-17
        • 1970-01-01
        • 2020-09-09
        • 2016-09-29
        • 2020-12-31
        • 2018-03-09
        • 1970-01-01
        相关资源
        最近更新 更多