jjzjj

javascript - 遍历 children 的 children 并为所有 input 添加函数,同时保持其他 children 不变

coder 2024-07-16 原文

我一直在尝试让它工作一段时间,但不确定如何执行以下操作。我的表单组件有包含常规 html 标记和输入的子组件。如果 child 是输入,我想添加 attachToFormdetachFromForm 函数。如果它不是输入,我想继续遍历子项以确保该元素没有子输入字段。无论该元素是否是输入,我仍然希望它出现在我的页面上,我只是想将功能添加到输入。

问题是我只能让我的函数只返回输入,删除标签和标题。我知道那是因为我只向 newChildren 添加带有输入的元素,但是如果我将其他元素推送到 else if 部分,我会得到重复项,我可以想到另一种方法来执行此操作。我不确定我是不是不了解基本的 JS 还是脑子有问题。

React.Children.forEach(children, function(child) {
        var current = child;
        if (child.props && child.props.name) {
            this.newChildren.push(React.cloneElement(child, {
                detachFromForm: this.detachFromForm,
                attachToForm: this.attachToForm,
                key: child.props.name
            }));
        } else if (child.props && child.props.children){
            this.newChildren.push(child);
            this.registerInputs(child.props.children);
        } else {
            *need to keep track of parent elements and elements that do not have inputs
        }
    }.bind(this));

编辑:不确定是否需要,但这是我正在遍历的示例形式

return ( 
            <Modal className="_common-edit-team-settings" title={`Edit ${this.props.team.name}`} isOpen={this.props.modalIsOpen && this.props.editTeamModal} onCancel={this.props.toggleEditTeamModal} backdropClosesModal>

                <Form onSubmit={this.saveChanges}>      
                    <FormSection className="edit-team-details" sectionHeader="Team Details">
                        <FormField label="Name">
                            <Input name="name" value={this.state.values.name} onChange={this.handleInputChange} type="text" placeholder={this.props.team.name}/>
                        </FormField>
                        <FormField label="Mission">
                            <Input name="mission" value={this.state.values.mission} onChange={this.handleInputChange} type="text" placeholder={this.props.team.kitMission || 'Kit Mission'} multiline />
                        </FormField>
                    </FormSection>

                    <FormSection className="privacy-settings" sectionHeader="Privacy Settings">
                        <FormField label="Included in global search results" >
                            <SlideToggle name="globalSearch" defaultChecked={this.state.values.globalSearch} onChange={this.handleCheckedChange} type="checkbox" />
                        </FormField>
                        <FormField label="Accessible by anyone" >
                            <SlideToggle name="public" defaultChecked={this.state.values.public} onChange={this.handleCheckedChange} type="checkbox" />
                        </FormField>
                        <FormField label="Secured with WitCrypt" >
                            <SlideToggle name="witcryptSecured" defaultChecked={this.state.values.witcryptSecured} onChange={this.handleCheckedChange} type="checkbox" />
                        </FormField>
                    </FormSection>
                    <FormSection sectionHeader="Participants">
                        {participantsList}
                        <div id="add-participant" className="participant" onClick={this.toggleAddParticipantModal}>
                            <span className="participant-avatar" style={{backgroundImage:'url(/img/blue_add.svg)'}}></span>
                            <span>Add a Participant</span>
                            <span className="add-action roll"><a></a></span>
                        </div>
                    </FormSection>
                    <Button type="hollow-primary" size="md" className="single-modal-btn" block submit>Save</Button>
                </Form>


                <AddParticipant people={this.props.people} toggleAddParticipantModal={this.props.toggleAddParticipantModal} modalIsOpen={this.props.modalIsOpen} toggleAddParticipantModal={this.toggleAddParticipantModal} addParticipantModal={this.state.addParticipantModal} />
            </Modal>
        );

顺便说一句,我开始时想做以下事情要简单得多,但得到:

"Can't add property attachToForm, object is not extensible"

如果有人知道为什么请告诉我。

registerInputs: function (children) {

    React.Children.forEach(children, function (child) {

      if (child.props.name) {

        child.props.attachToForm = this.attachToForm;
        child.props.detachFromForm = this.detachFromForm;
      }

      if (child.props.children) {
        this.registerInputs(child.props.children);
      }
    }.bind(this));
  }

最佳答案

从错误信息来看,你的不可变prop对象有问题。从 React 0.14 开始,prop 被“卡住”:

The props object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, React.cloneElement should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.

Blog post on this

因此,在您的代码中某处,您尝试扩展 prop 对象导致错误。

您可以使用 try..catch 结构包装您的 prop 交互的不同部分,这将指出您确切的问题所在。

关于javascript - 遍历 children 的 children 并为所有 input 添加函数,同时保持其他 children 不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33702815/

有关javascript - 遍历 children 的 children 并为所有 input 添加函数,同时保持其他 children 不变的更多相关文章

  1. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  2. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  3. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  4. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  5. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  6. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  7. ruby - 调用其他方法的 TDD 方法的正确方法 - 2

    我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent

  8. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  9. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  10. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

随机推荐