在React中委托模式 - 如何实现它?

时间:2017-06-12 07:01:11

标签: reactjs

我主要是一名C ++开发人员,我很难理解如何在React中创建一个“委托”。

我想要实现的目标:将自定义组件传递给具有所需代码的表组件,以正确编辑表格单元格上的数据。

在我的mainApp上:

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

代码要短得多。

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 ++程序员。

1 个答案:

答案 0 :(得分: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>)
    }
}

作为旁注。

我认为你不需要复制并让你的“代表”处于州内。他们不太可能改变?如果是这样 - 只需将它们留在道具中。