React - Components using Javascript

一曲冷凌霜 提交于 2019-12-13 03:49:53

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/44770640/react-components-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!