如何使用react-hook设置状态功能?

时间:2019-08-30 06:58:41

标签: reactjs react-hooks

我正在使用类组件,我想切换到功能组件(使用钩子)。当我使用类组件并单击网格的行时,将显示模式。当我将函数组件与钩子一起使用时,它显示错误“模式不是函数”

class MyGrid extends Component {
  state = {
    loading: false,
    rowData: [],
    columnDefs: [{headerName: 'Title', field: 'title'}, {headerName: 'Count', field: 'count'}],
    modal: null
  }

  //event click on row
  onRowSelected = (lol) => {    
     this.state.modal(lol)
  }

  render(){
    return (
        <>
          <Modal
            getOnOpen={callback => this.setState({modal: callback})}
          />
          <div style={{ height: '500px' }}>
            <Grid
              columnDefs={this.state.columnDefs}
              rowData={this.state.rowData}
              onGridReady={params => {
              params.api.sizeColumnsToFit()
              }}
              onRowSelected={this.onRowSelected}
            />
          </div>
       </>
    )
  }
}


export default MyGrid

还有我的功能组件。这是错误的

function MyGrid(props) {
  const [modal, setModal] = useState(null)
  const [rowData, setRowData] = useState([])
  const columnDefs = [{headerName: 'Title', field: 'title'}, {headerName: 'Count', field: 'count'}]

  //event click on row
  function onRowSelected(lol){    
     modal(lol)
  }
    return (
        <>
          <Modal
            getOnOpen={callback => setModal(callback)}
          />
          <div style={{ height: '500px' }}>
            <Grid
              columnDefs={columnDefs}
              rowData={rowData}
              onGridReady={params => {
              params.api.sizeColumnsToFit()
              }}
              onRowSelected={onRowSelected}
            />
          </div>
       </>
    )
}


export default MyGrid

请帮助我

1 个答案:

答案 0 :(得分:0)

此代码。模态为空

  function onRowSelected(lol){    
     modal(lol)
  }

转换为此

function onRowSelected(lol){    
     setModal(lol)
  }