表格在ReactStrap模态设置状态

问题描述 投票:0回答:1

我试图用一个表格来显示一个新的音符模态。我正在将包含表单的JSX传递给模态,输入的onChange方法触发但不更新状态。我看到事件使用console.log以及name和value的值启动,但状态不会更新。任何帮助将不胜感激。

Modal.js

import React from "react";
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";

export default function MyModal(props) {
  return (
    <Modal isOpen={props.isOpen}>
      <ModalHeader>{props.modalTitle}</ModalHeader>
      <ModalBody>{props.modalBody}</ModalBody>
      <ModalFooter>
        <Button color="primary" onClick={props.modalAction}>
          Yes
        </Button>{" "}
        <Button color="secondary" onClick={props.handleModal}>
          Cancel
        </Button>
      </ModalFooter>
    </Modal>
  );
}

LeadView.js

export class LeadView extends Component {
  constructor() {
    super()
    this.state = {
      result: '',
      message: '',
      note: '',
      modal: false,
      modalTitle: '',
      modalBody: '',
      modalAction: '',
    }
  }
  handleChange = event => {
    console.log('name', event.target.name)
    console.log('value', event.target.value)

    const { name, value } = event.target
    this.setState({
      [name]: value,
    })
  }

  handleModalForNote = () => {
    this.setState({
      modal: !this.state.modal,
      modalTitle: 'New Note',
      modalBody: (
        <div className="form-group">
          <input
            type="text"
            className="form-control"
            onChange={this.handleChange}
            name="note"
            value={this.state.note}
          />
        </div>
      ),
      modalAction: this.handleCallClick,
    })
  }

  render() {
    return (
      <Fragment>
        <MyModal
          handleModal={this.handleModalClose}
          modalAction={this.state.modalAction}
          isOpen={this.state.modal}
          modalBody={this.state.modalBody}
          modalTitle={this.state.modalTitle}
          modalOptions={this.state.modalOptions}
        />
        <button onClick={this.handleModalForNote} className="btn btn-primary">
          Write Note
        </button>
      </Fragment>
    )
  }
}
reactjs reactstrap
1个回答
0
投票

当您将函数handleChange赋予输入时,您只传递函数本身。然后,当您将该JSX提供给Modal时,它的执行理念是它应该在Modal Component中执行它所执行的任何代码。您需要做的是通过执行当前上下文

onChange={this.handleChange .bind(this)}

这会将组件的“上下文”绑定到函数,以便现在无论在何处调用它,它都将在LeadView组件的上下文中执行。

你应该记住你传递函数的其他地方。

© www.soinside.com 2019 - 2024. All rights reserved.