【问题标题】:Reactjs and antd modals - code issuesReactjs 和 antd modals - 代码问题
【发布时间】:2017-07-10 15:15:00
【问题描述】:

我是 reactjs 新手,我正在尝试使用 antd 的模态功能。但是,当我将基本示例代码合并到我的代码库中时,我遇到了一些错误——我不得不删除冒号、尾随逗号,并且状态变量出现错误。

https://ant.design/components/modal/

import { Modal, Button } from 'antd';

class App extends React.Component {
  state = { visible: false }
  showModal = () => {
    this.setState({
      visible: true,
    });
  }
  handleOk = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }
  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }
  render() {
    return (
      <div>
        <Button type="primary" onClick={this.showModal}>Open</Button>
        <Modal
          title="Basic Modal"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <p>Some contents...</p>
          <p>Some contents...</p>
          <p>Some contents...</p>
        </Modal>
      </div>
    );
  }
}

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

我的错误是语法错误?我尝试在构造函数中设置状态,但未定义。

client:119 ./src/components/Video/VideoConference.js
Module build failed: SyntaxError: D:/wamp/www/e-profound-react/src/components/Video/VideoConference.js: Unexpected token (631:8)

  629 |   }
  630 | 
> 631 |   state = { visible: false }
      |         ^
  632 |   showModal () {
  633 |     this.setState({
  634 |       visible: true,

 @ ./src/router.js 35:0-65
 @ ./src/index.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./index.js

我的代码看起来更复杂,但看起来像这样。

class VideoConference extends React.Component {

  constructor (props) {
    super(props)
  }

  componentWillMount () {

  }

  componentWillUnmount () {
  }

  componentDidMount () {
  }

  state = { visible: false }
  showModal () {
    this.setState({
      visible: true,
    })
  }
  handleOk (e) {
    console.log(e)
    this.setState({
      visible: false,
    })
  }
  handleCancel (e) {
    console.log(e)
    this.setState({
      visible: false,
    })
  }

  render () {

    return (
      <div>
        <Spacers />

        <Button type='primary' onClick={this.showModal}>Open</Button>
        <Modal
          title='Basic Modal'
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <p>Some contents...</p>
          <p>Some contents...</p>
          <p>Some contents...</p>
        </Modal>

      </div>
    )
  }
}

【问题讨论】:

    标签: reactjs modal-dialog antd


    【解决方案1】:

    您的示例显示了如何在contructor 方法之外使用state。这称为class properties,不是ES6 规范的一部分。

    首先你应该知道标准/默认的 react ES6 类语法:

    // example code here
    import React, { Component } from 'react';
    
    class App extends Component {  // same as React.Component
      constructor(props) {
        super(props); // you always need to call super();
    
        this.state = {
          visible: false,
        }
      }
    
      // other methods, lifecycle methods, render method etc.
      // ...
    }
    

    要使用class properties,你需要安装一个babel插件babel-plugin-transform-class-properties。有关示例和安装指南,请转到 here

    如果你使用webpack2 这是我的 babel 设置。可能对你有用:

    ...
    module: {
      rules: [
        // .js(x) loading
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          use: [
            {
              loader: 'babel-loader',
              query: {
                // Ignore the .babelrc at the root of our project-- that's only
                // used to compile our webpack settings, NOT for bundling
                babelrc: false,
                presets: [
                  ['env', {
                    // Enable tree-shaking by disabling commonJS transformation
                    modules: false,
                    // Exclude default regenerator-- we want to enable async/await
                    // so we'll do that with a dedicated plugin
                    exclude: ['transform-regenerator'],
                  }],
                  // Transpile JSX code
                  'react',
                ],
                plugins: [
                  'transform-object-rest-spread',
                  'syntax-dynamic-import',
                  'transform-regenerator',
                  'transform-class-properties',
                  'transform-decorators-legacy',
                ],
              },
            },
          ],
        },
      ],
    },
    ...
    

    【讨论】:

    • --你把方法放在babel-loader的这一部分?
    • 我的 babel 加载器看起来很简单? -- { include: resolve('src'), test: /\.js$/, loader: 'babel-loader', exclude: '/node_modules' },
    • 保持原样。如果你不明白我的配置。为你工作。阅读此处babeljs.io/docs/plugins/transform-class-properties,您可以使用.babelrc 文件添加此babel 插件。
    • @TheOldCounty 回答您的问题is there a way of invoking these modals - just like jquery -- $('#feedback').modal():我认为&lt;Modal title="Basic Modal" visible={this.state.visible} 这个visible 道具具有显示/隐藏您的模态的逻辑。因此,如果您实施 state.visible 切换,那么您就可以开始了。
    • 我认为这里会发生什么 - 是否会加载 - 隐藏标记 - 所以 - 会是创建多个状态/可见的情况吗? -- this.feedbackstate.visible -- this.feedbackthankyou.visible?
    【解决方案2】:

    你必须把初始状态放在类构造函数中(https://facebook.github.io/react/docs/state-and-lifecycle.html

    constructor(props){
      super(props);
      this.state = { visible: false }
    }
    

    【讨论】:

    • 当我这样做时 - 它变得未定义
    • “未捕获的类型错误:无法读取未定义的属性 'setState'”
    • -- 所以当我点击按钮时 -- showModal 函数会弹出这个
    • 对不起,我弄错了。现在试试,我编辑了代码。
    • 句柄的函数不在类的上下文中。您必须在这些函数中绑定上下文 this。我在构造函数中这样做,this.handleCancel = this.handleCancel.bind(this)。
    【解决方案3】:

    反应initial state & ES 6 类

    import { Modal, Button } from 'antd';
    
    class App extends React.Component {
      constructor(props){
          super(props);
          this.state  = {
              visible: false
          };
      }
      showModal = () => {
        this.setState({
          visible: true,
        });
      }
      handleOk = (e) => {
        console.log(e);
        this.setState({
          visible: false,
        });
      }
      handleCancel = (e) => {
        console.log(e);
        this.setState({
          visible: false,
        });
      }
      render() {
        return (
          <div>
            <Button type="primary" onClick={this.showModal}>Open</Button>
            <Modal
              title="Basic Modal"
              visible={this.state.visible}
              onOk={this.handleOk}
              onCancel={this.handleCancel}
            >
              <p>Some contents...</p>
              <p>Some contents...</p>
              <p>Some contents...</p>
            </Modal>
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, mountNode);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2019-11-18
      • 1970-01-01
      • 2021-09-18
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 2019-08-09
      相关资源
      最近更新 更多