【问题标题】:How can i pass multiple thing in one props from child to parent?如何将一个道具中的多个东西从孩子传递给父母?
【发布时间】:2020-07-10 19:43:30
【问题描述】:

我有一个子组件,我想用一个道具制作多个东西, 主要思想是我的子组件我有这个我想传递给父组件的项目,同时我想关闭模式“从父组件更改状态”。

那我该如何处理呢?

Const Child =(props) => {
        const [itemSelected,setItemSelected] = useState(null);
    
    const passData= ()=>{
        ....
        // I want here to send item selected and call a function from parent 
       // props.onPress( itemSelected, and let parent to call a function )
     }

   return (
      <Button onPress={passData} />
}


Const Parent = ()=>{
     Const sendData = ()=>{
         // Change parent state "close modal"
         // get data from child and send it to Api 
      }

     return (
       <Child onPress={sendData} />
     );
}

【问题讨论】:

  • 在父级中 - 更新 sendData 以接受参数 itemSelected。在孩子中 - 从passData 致电props.onPress(itemSelected)
  • @himayan 感谢它的作品,你能解释一下吗?我为什么要通过itemSelected 传递props. onPress()
  • 当然。我已经发布了更详细的答案。我希望它有所帮助。 @Oliver D.

标签: javascript reactjs react-native


【解决方案1】:

React 中将数据从 Child 传递到 Parent 的理想方法是通过作为 props 传递的函数。 我认为,这让您感到困惑的主要原因之一是您使用的函数的命名。 为了便于理解,我将传递为onPressprop 重命名为sendData。让我们看看它是否让事情变得更容易。所以,这是你的组件 -

儿童

Const Child =(props) => {
   const [itemSelected,setItemSelected] = useState(null);
   const passData = () => {
        ....
        props.sendData(itemSelected);
        // calling the function (sendData) received from Parent as a prop
        // with the data (itemSelected) from Child
   }

   return (
      <Button onPress={passData} />
   )
}

家长

const Parent = () => {
     const sendData = (itemSelected) => {
        // itemSelected is the data which you are receiving from Child
        // this function will be called from Child with the data passed as parameter
     }

     return (
        <Child sendData={sendData} />
        // sending the function to child
     )
}

【讨论】:

  • 嘿@himayan 再次:3,我只是有一个更新:D 现在正如您在孩子中所说的那样,我可以在参数函数中传递任何道具,所以在父母中我可以在您在这里写的时候收到它@ 987654329@现在,我怎样才能在其他功能中使用这个itemSelected?当我想将此项目设置为状态时,我收到此警告cannot update a component from inside the function body of a different component
【解决方案2】:

当你想从孩子更新父母时,你可以这样做:


const Child = ({update}) => {
    
    update("foo", "bar");
    
    return (
        <Text> Test </Text>
    )  
}
const Parent = () => {
     const [foo, setFoo] = useState('');
     const [bar, setBar] = useState('');

     const update = (f, b) => {
        setFoo(f);
        setBar(b);
     }
 
     return (
       <>
         <Child update/>
       </>
     }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    相关资源
    最近更新 更多