尝试学习React和Reactstrap并尝试使Modals工作。当我单击按钮时,它应该切换模态,但是现在它给了我这个错误:元素类型无效:期望使用字符串(对于内置组件)或类/函数(对于复合组件),但是得到:未定义。检查“应用”的渲染方法

无法弄清楚我在做什么错。有人可以帮我知道我在哪里出问题了吗?感谢您可以提供的任何帮助。

如果可能的话,我想使用最新版本的React和Reactstrap。

这是Codepen上的链接:https://codepen.io/lieberscott/pen/ddYNVP

const { Button,
       Container,
       Modal,
       ModalTitle,
       ModalHeader,
       ModalBody,
       ModalFooter } = Reactstrap;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showModal: false
    }
    this.toggleModal = this.toggleModal.bind(this);
  }

  toggleModal() {
    console.log("hello");
    this.setState({
      showModal: !this.state.showModal
    })
  }

  render() {
    return (
      <Container>
        <Headline />
        <Box />
        <Button outline color="primary" onClick={this.toggleModal}>Click</Button>
        <Modal isOpen={this.state.showModal} toggle={this.toggleModal} className="modal">
          <ModalHeader>
            <ModalTitle id="modalTitle">
              Add a Recipe
            </ModalTitle>
          </ModalHeader>
          <ModalBody>
            Modal body
          </ModalBody>
          <ModalFooter>
            Modal footer
          </ModalFooter>
        </Modal>
      </Container>
    );
  }
}

class Headline extends React.Component {
  render() {
    return (
      <div>
        Recipes
      </div>
    );
  }
}

class Box extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [
        {
        name: "Tofu tacos",
        ingredients: [
          "Shells",
          "lettuce",
          "tofu",
          "paprika"
        ]
      },
      {
        name: "Spaghetti",
        ingredients: [
          "pasta",
          "sauce",
          "salt"
        ]
      }
      ] // end of items
    } // end of this.state
  } // end of constructor
  render() {
    const allitems = this.state.items.map(item => {
      return (
        <div>
          {item.name}
        </div>
      );
    })
    return (
      <div>
        {allitems}
      </div>
    );
  }
}

const app = document.getElementById("app");

ReactDOM.render(<App />, app);

最佳答案

很抱歉,我不知道如何通过Codepen共享我的代码。

我做了这些更改:

toggleModal() {
    console.log("hello");
    console.log( 'before setState: ', this.state );
    this.setState({
      showModal: !this.state.showModal
    })
    console.log( 'after setState: ', this.state );
  }

Button onClick事件,当您执行onClik={this.something}时,此this引用Button元素。我改为:
<Button outline color="primary" onClick={() => this.toggleModal()}>Click</Button>

当我这样做时,onClick={ () => this.something() }允许我使用我的类的方法。

只需查看console.log输出,您就会看到单击按钮,将showModal更改为truefalse

看看头颅化的答案:https://forum.freecodecamp.org/t/difference-in-reactjs-onclick-function-binding/116027/2

关于javascript - Reactstrap:使模态工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48567247/

10-11 12:13