简体   繁体   中英

React - Components using Javascript

I am trying to figure out how to respond to the warning in react to use javascript classes to create components in my MERN app.

The warning says:

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]

The link in that message says:

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

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

I am using react v 15.5.4

In my app, I have tried to change my components as follows:

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();

However, the warning persists. Can anyone see what I have done wrong? How do I implement the new approach to defining components?

You should use ES6 class for make a React component.

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>
    }
}

This is what I would do to create a class in React:

import React, { Component } from 'react';

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM