2015-09-07 62 views
0

我試圖做一個項目我工作的一個簡單的表格系統,而且想法很簡單。我有一個FormStore表單可以註冊,組件可以註冊到這些表單,並可以檢索所有的數據。ReactJS:訪問孩子的方法

我想使這個儘可能地自動化,所以當<Form>元件被安裝,它應該尋找任何孩子的isFormItem財產,並自動與一些回調寄存器輸入字段得到的值,輸入中定義元件。

我現在面臨的問題是,我不知道我怎麼會從更高的層次組件訪問的子組件。我認爲沒有辦法使用裁判,因爲那些裁判必須手動分配,這就是我想要避免的。

這是從我的Form.react.jsx相關片段。這是我嘗試將每個輸入字段附加到表單的位置。

componentDidMount() { 
    const name = this.props.name || 
     'form_' + Math.floor(Math.random() * 100000000); 
    FormStore.registerForm(name); 
    React.Children.forEach(this.props.children, (child) => { 
     if (selectn('props.isFormItem', child)) { 
     // I need to call child.attachToForm somehow... 
     } 
    }); 
    }; 

這些是Input.react.jsx的相關部分。

constructor(props) { 
    this.attachToForm = this.attachToForm.bind(this); 
    } 

    attachToForm(formName) { 
    const name = this.props.name || 
     'formItem_' + Math.floor(Math.random() * 100000000); 
    FormStore.attachToForm(formName, name,() => this.state.value); 
    } 

我試圖訪問的子組件的方法是這樣的:

React.Children.forEach(this.props.children, (child) => { 
    if (selectn('props.isFormItem', child)) { 
     child.type.prototype.attachToForm = 
     child.type.prototype.attachToForm.bind(child); 
     child.type.prototype.attachToForm(name); 
    } 
    }); 

但調用的原型不實際的對象實例綁定的任何地方,這樣在有一大堆綁定結束了無處不在,最終它除了四處亂糟糟外,沒有任何工作。

是否有這樣做的一些方法?我只是沒有看到它...任何幫助,將不勝感激。

回答

1

您可以通過formName爲道具,以每個Input組件,然後在它自己的componentDidMount方法附上每個項目來代替。

此外,getDefaultProps方法似乎在你的情況下派上用場。

喜歡的東西:

getDefaultProps() { 
    return { 
    name: 'form_' + Math.floor(Math.random() * 100000000) 
    } 
} 
render() { 
    return <Input formName={this.props.name} /> 
} 

然後在輸入組件:

getDefaultProps() { 
    return { 
    name: 'formItem_' + Math.floor(Math.random() * 100000000) 
    } 
} 
componentDidMount() { 
    FormStore.attachToForm(this.props.formName, this.props.name,() => this.state.value) 
} 
+0

是的,好像我會採取不同的方法畢竟。我想過這樣做,但這仍然會讓額外的工作不得不爲每個輸入編寫formName prop。我想我會用克隆的元素替換輸入元素,並在那裏執行任何附加操作。似乎沒有什麼麻煩。 – Pavlin

+0

我更喜歡添加道具的詳細方式,或者只是將它們添加到「地圖」循環中。代碼將更加清晰和容易維護。 – David