2017-06-12 48 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

感谢您的回复。我想在这里看看如何应用这个。 –