Javascript 如何在一个道具中将多个道具从孩子传递给家长?

Javascript 如何在一个道具中将多个道具从孩子传递给家长?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我有一个子组件,我想从一个道具制作多个东西, 主要的想法是我的子组件我有一个项目,我想传递给家长,同时我想关闭模态“改变状态从家长” 那我怎么处理呢 Const Child =(props) => { const [itemSelected,setItemSelected] = useState(null); const passData= ()=>{ .... // I want here to send item

我有一个子组件,我想从一个道具制作多个东西, 主要的想法是我的子组件我有一个项目,我想传递给家长,同时我想关闭模态“改变状态从家长”

那我怎么处理呢

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} />
     );
}
Const Child=(道具)=>{
const[itemSelected,setItemSelected]=useState(null);
常量passData=()=>{
....
//我想在这里发送所选项目并从父级调用函数
//onPress(itemSelected,并让父对象调用函数)
}
返回(
}
常量父项=()=>{
Const sendData=()=>{
//更改父状态“关闭模式”
//从子级获取数据并将其发送到Api
}
返回(
);
}

当您想从子对象更新父对象时,可以执行以下操作:


const Child=({update})=>{
更新(“foo”、“bar”);
返回(
试验
)  
}
常量父项=()=>{
const[foo,setFoo]=useState(“”);
const[bar,setBar]=使用状态(“”);
常数更新=(f,b)=>{
setFoo(f);
挫折(b);
}
返回(
}
}

React中,将数据从
传递到
的理想方法是通过作为
道具传递的函数。
我认为,这让您感到困惑的主要原因之一是您使用的函数的命名。
为便于理解,我已将作为
onPress
传递的
prop
重命名为
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 Child=(道具)=>{
const[itemSelected,setItemSelected]=useState(null);
常量passData=()=>{
....
props.sendData(itemSelected);
//调用作为道具从父级接收的函数(sendData)
//使用来自子对象的数据(itemSelected)
}
返回(
)
}
家长

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
     )
}
const Parent=()=>{
const sendData=(itemSelected)=>{
//itemSelected是您从子系统接收的数据
//此函数将通过作为参数传递的数据从子级调用
}
返回(
//将函数发送给子对象
)
}

在parent-update
sendData
中接受一个参数
itemSelected
。在child-call
props.onPress(itemSelected)
from
passData
@himayan感谢它的工作,你能再解释一下吗?我为什么要通过
props.onPress()传递
itemSelected
当然可以。我已经发布了一个更详细的答案。我希望它能有所帮助。@Oliver D.hey@himayan再次:3,我现在有一个更新:D,正如您所说,在一个子函数中,我可以传递参数函数中的任何道具,所以在父函数中,我可以在您在这里编写时接收它。
sendData=(itemSelected)=>{..}
现在,我如何在其他功能中使用此项Selected?当我想将此项设置为状态时,我收到此警告
无法从其他组件的功能体内部更新组件