簡體   English   中英

React-使用Javascript的組件

[英]React - Components using Javascript

我試圖弄清楚如何響應警告以使用javascript類在我的MERN應用中創建組件。

警告說:

Warning: Accessing createClass via the main React package is deprecated, and will be removed in React v16.0. Use a plain JavaScript class instead. If you're not yet ready to migrate, create-react-class v15.* is available on npm as a temporary, drop-in replacement. For more info see[ \[this link\][1]

該消息中的鏈接顯示:

// After (15.5)
var React = require('react');
var createReactClass = require('create-react-class');

var Component = createReactClass({
  mixins: [MixinA],
  render() {
    return <Child />;
  }
});

我正在使用React v 15.5.4

在我的應用中,我嘗試如下更改組件:

import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'react-bootstrap';

var createReactClass = require('create-react-class');


var GreeterForm = createReactClass({
  onFormSubmit: function(e) {
    e.preventDefault();

但是,警告仍然存在。 誰能看到我做錯了嗎? 如何實現定義組件的新方法?

您應該使用ES6類來制作React組件。

import React from 'react';

class App extends from React.Component{
    constructor(props){
        super(props);
        this.sample = this.sample.bind(this);
        // initialize your methods, states here
    }

    // if you want life cycle methods and methods define here

    componentWillMount(nextProps, nextState){
        console.log('componentWillMount');
    }

    sample(){
        console.log('sample');
    }

    render(){
        return <div onClick={this.sample}>Hello World!</div>
    }
}

這就是我要在React中創建一個類的方法:

import React, { Component } from 'react';

class GreeterForm extends Component {
    onFormSubmit = (e) => {
        e.preventDefault();
        //do stuff
    }
    render() {
        return (<Child onFormSubmit={this.onFormSubmit} />)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM