更新所有反应子组件

时间:2018-11-25 14:05:44

标签: reactjs typescript3.0

我有这样的代码:

<Editor source="/api/customer" onCreate={this.debugChange} onDelete={this.debugChange} onUpdate={this.debugChange}>
    <Group title="Address">
        <Column id="id" label="ID" default={0} readonly />
        <Column id="name" label="name" default="" />
        <Column id="address" label="Address" default="" />
        <Column id="country" label="Country" default={currentCountry} readonly source="/api/country" idfield="id" captionField="name" />
    </Group>
    <Group title="Payment">
        <Column id="tax" label="TaxType" default={0} source="/api/taxtype" idfield="id" captionField="name" />
        <Column id="bank" label="Bank" default="" source="/api/banks" idfield="id" captionField="bank"/>
        <Column id="account" label="Account Number" default="" />
    </Group>
</Editor>

编辑器具有render()这样的功能:

    let components = React.Children.map(this.props.children, (child) => {
        return <Column {...child.props} default={row[child.props.id]} onChange={this.onChange.bind(this)} />
    })

    return <div className="hx-editor">
        <div className="hx-editor-list">
            <List id={this.props.id + "-list"} source={this.props.source}
                singleShow captionField={this.caption.bind(this)}
                groupfn={this.props.group} onSelect={this.onSelect.bind(this)} />
        </div>
        <form name={"hx-form-" + this.props.id} className="hx-form">
            {components}
            {buttons}
        </form>
    </div >

我在<List>的{​​{1}}

中具有这样的功能
onSelect

private onSelect(id: string, data: T) { this.setState({ currentRow: data, modifiedRow: data }) } 将显示<Editor>中带有/api/customer的列表,并将选定的值发送到<List>道具,后者依次更新所有onSelect的孩子。数据与列的ID相对应,例如:

<Column>

我在这里介绍的这种方法仅适用于直接位于data = [{ id: 0, name: 'My Customer', address: 'This is Address', country: 'US', tax: '010', bank: 'HSBC', account:: '89238882839304' }, ... ] 下的孩子,而不适用于<Editor>下的孩子。

我的问题是,当用户单击<Group>中的某个值时,如何对<Column>作为<Editor>的孩子的所有值进行深度更新。我的意思是,只要在<List>标记内,就对所有子项执行<Column>搜索,并更新所有值,无论它们在哪里。

感谢您的帮助。谢谢

2 个答案:

答案 0 :(得分:0)

<Group /> as intermediate 'layer' will 'block change propagation` - this component is not 'consuming' any prop and is therefore not change aware.

You can/need:

  • change structure;
  • pass prop that will be changed (and will force updates in children);
  • use redux;
  • use context API.

答案 1 :(得分:0)

好吧...这会破坏Typescript,我不知道如何在Typescript中正确键入它,但是这一方法可行。

private deepColumn(children: React.ReactNode) => any) {
    return React.Children.map(children, child => {
        if (child.props.children) {
            child = React.cloneElement(child, {
                children: this.deepColumn(child.props.children)
            })
        }
        if (child.type.name == "Column") {
            return <Column {...child.props} default={this.default} onChange={this.onChange.bind(this)} />
        } else return child;
    })
}