在React中将方法从一个组件移动到另一个组件,并且仍然可以在原始版本中使用 [英] Move method from one component to another in React and still be able to use in original

查看:85
本文介绍了在React中将方法从一个组件移动到另一个组件,并且仍然可以在原始版本中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React与ES6创建一个小型联系人应用程序.我在组件的渲染功能中显示了一些数据-有关原始结构,请参见以下问题的链接...

I am working to create a small contact app using React with ES6. I had some data displaying in the render function of a component - see the link to the question below for the original structure...

但是,因为我也在同一页上放置了一个表单,并且需要更新状态下的数据,所以我不得不将数据移至更高级别的组件.

However, because I was also putting a form on the same page and I needed to update my data in state, I had to move the data to a higher level component.

现在我在遍历这些组件时遇到了麻烦,因此我的原始联系人列表显示在左侧.我必须删除contact-list组件上我的render函数中的大部分内容,因为它完全破坏了构建.

Now I'm having trouble traversing the components so that my original list of contacts shows up on the left. I had to remove most of what was in my render function on the contact-list component because it was completely breaking the build.

首先,这是带有表单的地址簿组件-该组件正在运行,都从状态中拉出了我最初的3个联系人,然后将新的联系人从表单中隐瞒到数组中. (这里仍然需要清理代码才能使UI正常工作...)

First, here is the address-book component with the form - this is working, both pulling in my initial 3 contacts from state, then concating new contacts from the form to the array. (Still need cleanup code here to make UI work right...)

import React from 'react';
import ContactList from './contact-list.jsx';
import ContactForm from './contact-form.jsx';
import ShortContact from './short-contact.jsx';

class AddressBook extends React.Component {

constructor() {
    "use strict";
    super();

    this.state = {
        showContacts: true,
        contacts: [
    {
        id: 1,
        fName: "aaa",
        lName: "aaaaa",
        imgUrl: "http://brainstorminonline.com/wp-content/uploads/2011/12/blah.jpg",
        email: "aaa@aaaa.com",
        phone: "999999999999"
    },
    {
        id: 2,
        fName: "bbbbb",
        lName: "bbbbbbb",
        imgUrl: "https://media.licdn.com/mpr/mpr/shrinknp_200_200/bbb.jpg",
        email: "bbb@bbb-bbb.com",
        phone: "888888888888"
    },
    {
        id: 3,
        fName: "Number",
        lName: "Three",
        imgUrl: "http://3.bp.blogspot.com/-iYgp2G1mD4o/TssPyGjJ4bI/AAAAAAAAGl0/UoweTTF1-3U/s1600/Number+3+Coloring+Pages+14.gif",
        email: "three@ccccc.com",
        phone: "333-333-3333"
    }
];
    };

}




render() {
    "use strict";
    return (
        <div className="row address-book">

            <div className="col-md-6">
                <ContactList  />
            </div>
            <div className="col-md-6">

                <button className='btn' id="contact-submit-button" type="submit" value="Create Contact">Create New Contact </button>



                <div>
                    <ContactForm  addContact={this._addContact.bind(this)}/>
                </div>
            </div>
        </div>

    );

}

_addContact (fName, lName, company, email, phone, imgURL) {
    "use strict";
    const contact = {
        id: this.state.contacts.length + 1,
        fName,
        lName,
        company,
        email,
        phone,
        imgURL
    };
    this.setState({ contacts: this.state.contacts.concat([contact]) });
}

_getContacts() {
    "use strict";
    return contactList.map((contact) => {
        "use strict";
        return (
            <ShortContact contact={contact} key={contact.id}/>)
    });
}

_getContactsTitle (contactCount) {
    "use strict";
    if(contactCount === 0) {
        return 'No Contacts';
    } else if (contactCount === 1) {
        return '1 contact';
    } else {
        return `${contactCount} contacts`;
    }
}

}

export default AddressBook;

但是,我的ContactForm组件中需要使用的底部2种方法_getContacts和_getContactsTitle-就是这样:

However, the bottom 2 methods _getContacts and _getContactsTitle are the ones that are needed in my ContactForm component - which is this one:

import React from 'react';
import ShortContact from './short-contact.jsx';




class ContactList extends React.Component {



render() {

    const contacts  = this._getContacts();


    return (
        <div>
            <h3>List of Contacts</h3>
            <h4 className="contact-count">{this._getContactsTitle((contacts.length))}</h4>
            <ul className="contact-list">
                {contacts}
            </ul>
        </div>
    );
    }
}

export default ContactList;

定义联系人以及通过<ul><h4>的const是破坏应用程序的原因,因为您可以看到它引用了来自其他组件的_getContactTitle方法以及_getContacts中的{contacts}方法.

The const that defines contacts as well as the <h4> through the <ul> is what breaks the app because as you can see it references the _getContactTitle method from the other component as well as {contacts} which is in the _getContacts method.

我猜想我需要做一些事情,例如将它们包装到函数中并传递给它们-但是我已经转过身,还不太明白在React中这将如何工作.任何帮助都将受到欢迎.谢谢!

I'm guessing I need to do something like wrap them into functions and pass them - but I've gotten turned around and can't quite see how that would work here with React. Any help would be welcome. Thanks!

推荐答案

您需要通过道具将联系人向下传递,而不是尝试在父级中向下传递联系人列表.我的意思是这个.

You need to pass the contacts down via props instead of trying to build the list of contacts in the parent to pass down. what I mean is this.

地址簿

render() {
    "use strict";
    let contacts  = this._getContacts();
-----------^---------------^----------- get the list in the parent
    return (
        <div className="row address-book">
            <div className="col-md-6">
                <ContactList contacts={contacts} />
-------------------------------^-----------^---- important part here
            </div>
            <div className="col-md-6">
                <button className='btn' id="contact-submit-button" type="submit" value="Create Contact">Create New Contact </button>
                <div>
                    <ContactForm  addContact={this._addContact.bind(this)}/>
                </div>
            </div>
        </div>

    );
}

然后在联系人列表"组件中仅将列表用作道具.

then in your CONTACT LIST component just use the list as props.

render() {
    let {contacts} = this.props;
------------^--------------^---- its in the props now
    let title = contacts.length > 1 ? `${contacts.length} contacts` : contacts.length === 1 ? '1 contact' : 'No Contacts';
    return (
        <div>
            <h3>List of Contacts</h3>
            <h4 className="contact-count">{title}</h4>
            <ul className="contact-list">
                {contacts}
            </ul>
        </div>
    );
    }
}

从此处可以删除contactTitle函数.让孩子渲染它,因为它知道数组的长度(因为它在props中).

from here you can remove the contactTitle function. let the child render that since it knows the length of the array (because its in props).

作为旁注,在_addContact函数中.无需创建新数组并将其与状态触点数组连接,只需将新数组推入当前状态即可.其更好的存储空间(即,无需创建新数组即可将新项目组合到该数组中).

As a side note, in your _addContact function. instead of creating a new array and concatenating it with the state contact array just push the new one onto the current state. its better storage (i.e. dont need to make a new array to combine a new item to the array).

this.setState({ contacts: this.state.contacts.push(contact) });

这篇关于在React中将方法从一个组件移动到另一个组件,并且仍然可以在原始版本中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆