【问题标题】:Form in ReactStrap Modal setting stateReactStrap Modal设置状态下的Form
【发布时间】:2019-07-08 23:26:40
【问题描述】:

我试图在新笔记中显示带有表单的模式。 我将包含表单的 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】:

    当您将函数handleChange 提供给输入时,您只传递了函数本身。然后,当您将该 JSX 提供给 Modal 时,它正在执行的想法是,它正在执行的任何代码都应该在 Modal 组件中执行。你需要做的就是通过当前上下文来传递

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

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

    在传递函数的其他地方也应该记住这一点。

    【讨论】:

    • 即使函数在更改时运行?当我键入内容时,我可以在控制台日志中看到名称和值,它只是不会更新状态。我也尝试添加 .bind(this) 但这不起作用
    猜你喜欢
    • 2018-07-12
    • 2017-04-07
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2021-08-14
    • 2020-07-05
    • 2021-01-11
    • 1970-01-01
    相关资源
    最近更新 更多