如何使用onClick事件将道具从子组件传递到父组件React Hooks

时间:2020-08-24 14:27:26

标签: reactjs react-hooks react-props

PopupButtonTesting.js

const PopupButtonTesting = ({metaData, items, render}) = {
 const [open,toggle] = useButtonToggle({type: 'button1', open: false})'
 return (
  <>
   <ButtonBase metaData={metaData} onClick={toggle}>
    {open && items.map((m,i) => render(
       {...m.button1, 
       index:i, 
       onClose: toggle, 
       open})
     )}
  </>
 )
}

const ButtonBase = (mataData, onClick) => {
 const {dataField} = metaData
 return (
   <Button onClick={() => onClick('button1')}>
     show button1
   </Button>
| 
   <Button onClick={() => onClick('button2')}>
     show button2
   </Button>
 )
}

useButtonToggle.js

export default (initToggleState = {type: 'button1', open: false}) => {
  const [toggleState, setState] = useState(initToggleState);
  const toggle =setState(// add some logic here maybe);
  return [toggleState, toggle]
}

因此ButtonBase组件是PopupButtonTesting组件的子组件,因此在此子组件中呈现了两个按钮。我想单击button1并显示button1数据,而打开button2则显示button2数据,因此在ButtonBase中,我在onClick中传递了“ button1”和“ button2”,这对应于传递给{ {1}},然后我想修改ButtonBase以标识按钮类型,但是我不确定应该如何添加useButtonToggle

1 个答案:

答案 0 :(得分:0)

当您要将道具从孩子传递给父母时,最好的方法是通过函数参数调用

const someFunc = (varFromChild) => //do something

<ChildComponent funcToChild={(paramFromChild) => someFunc(paramFromChild) }

然后在ChildComponent中

onClick={() => props.funcToChild(something)}