我如何通过第一次渲染将所选状态放入树数据中

时间:2019-04-11 10:48:35

标签: reactjs material-table

我使用物料表,我想用物料表树数据呈现权限树

我的数据可能会这样

[
    {
      id: 1,
      name: 'a',
      type: 'adult',
      selected:true,
    },
    {
      id: 2,
      name: 'b',
      parentId: 1,
      selected:true,
    },
    {
      id: 3,
      name: 'c',
      parentId: 1,
      selected:true,
    },
    {
      id: 4,
      name: 'd',
      parentId: 3,
      selected:false
    },
    {
      id: 5,
      name: 'e',
      selected:false
    }
]

以及如何控制选中的左侧复选框

Screen shot of table

2 个答案:

答案 0 :(得分:0)

您应该为MaterialTable提供一个函数,以了解如何设置父对象。例如:

<MaterialTable
parentChildData={(row, rows) => rows.find(a => a.id === row.parentId)}
....
/>

使行默认为选中状态:

{ id: 5, name: 'e', tableData: { checked: true } }

答案 1 :(得分:0)

我阅读了一些问题,发现我可以在MaterialTable中设置“ tableRef”并在第一次设置选中状态,谢谢您

<MaterialTable
    tableRef={this.tableRolesRef}  //this.tableRolesRef=React.createRef();
    columns={[
        {title:"viewname",field:"viewname",sorting:false},
        {title:"modelname",field:"modelname",sorting:false,cellStyle:{whiteSpace:'nowrap'}},
        {title:"parentid",field:"parentid",sorting:false},
        {title:"id",field:"id",sorting:false},
        {title:"filename",field:"filename",sorting:false},
        {title:"version",field:"version",sorting:false},

    ]}
    actions={[
        {
            icon:'toggle_on',
            tooltip:'open',
            onClick:(event,rows)=>{console.log(rows,this.tableRef)}
        }
    ]}
    data={modules}
    title="permission"
    parentChildData={(row, rows) => rows.find(a => a.id === row.parentid)}
    onSelectionChange={data=>{console.log(data)}}
    options={{
        actionsColumnIndex:-1,
        toolbar:true,
        paging:true,
        selection:true
    }}
    localization={{...localization}}
/>

并在componentDidMount中得到我的答复

        redFetch(`rolepermission?roleid=${id}`)
            .then(res=>{
                this.setState({rolepermission:res})
                console.log(res)
                let renderData=this.tableRolesRef.current.state.renderData
                //renderData[0].tableData.checked=true
                //this.tableRolesRef.current.setState({renderData}) ←that is what i want to set
                console.log(this.tableRolesRef)

            })