澄清React继承

时间:2019-06-12 06:51:31

标签: reactjs inheritance

我在React中有一个继承案例,一个模块let credentials = { key: userinfo['secret'], algorithm: 'sha256', id: userinfo['id'] } 具有组件UserUserList并具有自己的功能,例如在UserList组件中显示userelist并在UserForm中提交表单。在项目/库的根部,它也有自己的动作,reducer。现在,我想在多个应用程序中使用此组件。 React中最好的选择是什么?到目前为止,我在继承方面所做的尝试:

  1. 创建的核心模块包括用户(UserList,UserCreat / Edit)组件。
  2. 将此核心模块包含在Project1 >> Src中
  3. 通过覆盖Core-UserCreate / Edit组件进行扩展

但是我不确定这是否是更好的解决方案。所以有人可以指导我如何以最佳方式实现功能吗?

UserForm

将UserCreatEdit表单继承到Project1中以扩展其功能和UI

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Form, ButtonToolbar, Col, Row, Button, Alert  } from "react-bootstrap";
import _ from 'lodash';

import fields from "./fields.json";

class UserCreateEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            fields: fields,
            label: "",
            name: "",
            type: "",
            placeholder: "",
            options: "",
            status:false,
            title:"Core:New User"
        };

        [
            "_handleSubmit",
            "_handleChange",
            "_handleFieldsSubmit",
            "_handleFieldsChange",
            "_handleCancel"
        ].map((fn) => this[fn] = this[fn].bind(this));
    }
    static propTypes = {
        fields: PropTypes.array
    };
    _handleSubmit(e) {
        e.preventDefault();
        const { label, name, type, placeholder, options } = this.state;

        this.setState((prevState) => ({
            fields: [
                ...prevState.fields, {
                    label,
                    name: name || `name--${prevState.fields.length}`,
                    type: type || "text",
                    placeholder,
                    options
                }
            ]
        }));
    }
    componentDidMount() {
        // const { fields, title } = this.props;
        // if(!_.isUndefined(fields)){
        //  this.setState({
        //      fields:[...fields]
        //  });
        // }
        // if(!_.isUndefined(title)){
        //  this.setState({
        //      title:[...title]
        //  });
        // }
    }
    _handleChange(e) {
        this.setState({ [e.target.name]: e.target.value });
    }

    async _handleFieldsSubmit(e) {
        e.preventDefault();
        console.log("json: ", JSON.stringify(this.state.fields));
        const obj = {};
        (Object.keys(this.refs) || []).forEach((i) => obj[this.refs[i].name] = this.refs[i].value || "");
        console.log('obj: ', obj);
        await this.props.saveUser({
            user: obj
        });
        console.log('"status" :', this.props.status);
        if(this.props.status){
            this.setState({
                status: this.state.status
            });
            this.props.history.push("/users");  
        }
    }
    _handleCancel = () => {
        this.props.history.push("/users");  
    } 
    _handleFieldsChange(e, i) { }
    render() {
        const fields = (this.state.fields || []).map((f, i) => {
            const { label, name, type, value: defaultValue, ...rest } = f;
            return (
                <Form.Group key={i} controlId={`form--${i}`}>
                    {(type !== "checkbox" && label) && <Form.Label>{label}</Form.Label>}
                    {(type === "checkbox") && (
                        <Form.Check
                            type={type}
                            name={`${name}`}
                            label={label}
                            defaultValue={defaultValue}
                            onChange={(e) => this._handleFieldsChange(e, i)}
                        />
                    )}

                    {(type !== "checkbox" && type !== "select") && (
                        <Form.Control
                            type={type}
                            name={`${name}`}
                            ref={`form__${name}__${i}`}
                            defaultValue={defaultValue}
                            onChange={(e) => this._handleFieldsChange(e, i)}
                            {...rest}
                        />
                    )}

                    {(type === "select") && (
                        <Form.Control
                            as="select"
                            name={`${name}`}
                            ref={`form__${name}__${i}`}
                            defaultValue={defaultValue}
                            onChange={(e) => this._handleFieldsChange(e, i)}
                        >
                            {(JSON.parse(f.options) || []).map((o) => <option key={o} value={o}>{o}</option>)}
                        </Form.Control>
                    )}
                </Form.Group>
            )
        });
        return (<div style={{ margin: 20 }}>
            <h4>{this.state.title}</h4>
            <Form className="mt-3 border-top py-3" onSubmit={this._handleFieldsSubmit} >
                {fields}
                {((this.state.fields || []).length > 0) && (
                    <ButtonToolbar>
                        <Button variant="primary" style={{ marginRight: 10 }} type='submit'>Save</Button>
                        <Button variant="danger" onClick={ () => this._handleCancel()}>Cancel</Button>
                    </ButtonToolbar>
                )}
            </Form>
        </div>);
    }
}

export default UserCreateEdit;

0 个答案:

没有答案