简体   繁体   English

如何使用子组件重新渲染父组件 onClick function

[英]How can I re-render parent component with a child component onClick function

I've got a parent component call "RiskMatrix.js" that looks as follows:我有一个名为“RiskMatrix.js”的父组件,如下所示:

export default function RiskMatrix({disable}) {

    const dispatch = useDispatch();
    const [risk_matrix, setRiskMatrix] = React.useState(useSelector((state) => state.riskMatrix.risk_matrix));

    if (disable == true) {
        return (
            
            <TableContainer component={Paper} style={{height: "40vh", width: "90vh"}}>
                {console.log(risk_matrix)}
                <Table size="small" sx={{ minWidth: 200 }}>
                    <TableHead>
                        <TableRow>
                            <TableCell align="center" width="90"></TableCell>
                            {consequences_description.map((description) => (
                                <TableCell align="center" width="90">{description}</TableCell>
                                )
                            )}
                        </TableRow>
                    </TableHead>
                    <TableBody>    
    
                        {risk_matrix.map((row, row_index) => (
                        <TableRow
                            key={row_index}
                            sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                        >
                            <TableCell component="th" scope="row">
                                {likelyhood_description[row_index]}
                            </TableCell>
                            {row.map( (column, column_index) => (
                                <TableCell align="center">
                                    <ToggleButton 
                                        risk={column}
                                        row_index={row_index}
                                        column_index={column_index}
                                        />
                                </TableCell>
                            ))}
                        </TableRow>
                        ))}
    
                    </TableBody>
                </Table>
            </TableContainer>
        );
    } else {
        return null
    }
}

I want this component to re-render when the child ("ToggleButton") components onClick function is called, the child component looks as follows:我希望此组件在调用子(“ToggleButton”)组件 onClick function 时重新呈现,子组件如下所示:

export default function ToggleButton({risk, row_index, column_index}) {

    const handleColor = () => {
        switch (risk){
            case "L":
              return "low"
            case "M":
              return "moderate"
            case "H":
              return "high"
            case "E":
              return "extreme"
            default:
              break;
        }
    };

    const dispatch = useDispatch();
    const { updateMatrix} = bindActionCreators(actions, dispatch)

    const handleOnClick = () => {
      switch (risk){
        case "L":
          updateMatrix(row_index, column_index, "M")
          break;
        case "M":
          updateMatrix(row_index, column_index, "H")
          break;
        case "H":
          updateMatrix(row_index, column_index, "E")
          break;
        case "E":
          updateMatrix(row_index, column_index, "L")
          break;
        default:
          break;
      }
    };

    return (

        <ThemeProvider theme={filtersTheme}>    
          <Button variant="contained" color={handleColor()} onClick={()=> handleOnClick()} >{risk}</Button>
        </ThemeProvider>
    );
}

The child component updates a react-redux state with the onClick function as well, ideally I would like the parent component to re-render once this state changes.子组件也使用 onClick function 更新 react-redux state,理想情况下我希望父组件在 state 更改后重新呈现。

React components re-render when the state is updated.当 state 更新时,React 组件会重新渲染。 So a solution would be to create a state and pass the setter to the child component and call it with a new value whenever a re-render is required.因此,解决方案是创建一个 state 并将 setter 传递给子组件,并在需要重新渲染时使用新值调用它。

you can also use Event bubbling in the parent element to capture the onClick event and update the state without needing to pass a prop to the child.您还可以在父元素中使用事件冒泡来捕获 onClick 事件并更新 state,而无需将 prop 传递给子元素。 read more about event bubbling here在此处阅读有关事件冒泡的更多信息

a better implementation would be using the react's context API so that each child has appropriate access to the matrix data and would be re-rendered when the data changes automatically.更好的实现是使用 react 的上下文 API,这样每个孩子都可以适当地访问矩阵数据,并在数据自动更改时重新呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM