2017-06-12 45 views
0

我大多是C++開發人員,我很難理解如何在React中創建一個「委託」。React中的委託模式 - 如何實現它?

我想實現的目標:將自定義組件傳遞給具有所需代碼以正確編輯表格單元格上的數據的表格組件。

我mainApp:

<TableComponent 
    headerData=["first", "second", "third"] 
    rowEditDelegates=[<input/>, <button></button>, <combobox/>] 
/> 

的代碼是brievety短得多。

class TableComponent extends React.Component { 
    constructor(props) { 
     super(props) 
     this.state = { 
      editDelegates = this.props.rowEditDelegates; 
      displayEditors = false; 
     } 

     onEditToogled() { 
      /* Here I have no idea how to get the editDelegates 
       and pass data to it. */ 
      setState({displayEditors : true}); 
     } 
    } 

    render() { 
     let row = null; 
     if(this.state.displayEditors) { 
      row = this.state.editDelegates.map((item) => <td> {item} </td>) 
     } else { 
      row = this.props.bodyData.map((item) => <td> {item} </td>) 
     } 
    } 
}; 

我無法訪問委託的方法,因爲它是一個渲染的成分,我不知道如何與組件「指針」的工作(我甚至不知道它的存在),也許我的問題需要與C++程序員不同的思維模式。

回答

0

你有幾個選擇這裏:

1)使用cloneElement功能:

onEditToogled() 
{ 
    setState({displayEditors : true}); 
} 

render() 
{ 
    let row = null; 
    if(this.state.displayEditors) 
    { 
     row = this.state.editDelegates.map((item) => { 
      var alteredElement = React.cloneElement(item, {className: "newPropertyValue"}); 
      return (<td> {alteredElement} </td>); 
     }); 
    } 
    else 
    { 
     row = this.props.bodyData.map((item) => <td> {item} </td>) 
    } 
} 

2)改變你如何通過編輯組件的方式,例如:

<TableComponent 
    headerData=["first", "second", "third"] 
    rowEditDelegates=[(props) => <input {...props}/>, (props) => <button {...props}/>, (props) => <combobox {...props}/>] 
/> 

後來:

render() { 
    let row = null; 
    if(this.state.displayEditors) { 
     row = this.state.editDelegates.map((itemFunc) => <td> {itemFunc({className: "newPropertyValue"})} </td>) 
    } else { 
     row = this.props.bodyData.map((itemFunc) => <td> {itemFunc()} </td>) 
    } 
} 

作爲一個方面說明。

我不認爲你需要複製並保留你的「代表」狀態。他們不太可能改變?如果是這樣 - 只要把它們放在道具中。

+0

感謝您的回覆。我想在這裏看看如何應用這個。 –