简体   繁体   English

从React中父组件的回调函数中的子组件访问变量,并在父组件中呈现返回的值

[英]Access variables from a child component in parent component's callback function in React and render the returned value in parent

How does the following situation work: 以下情况如何工作:

<FlatList
  data={[{key: 'a'}, {key: 'b'}]}
  renderItem={({item}) => <Text>{item.key}</Text>}
/>

Here, FlatList receives a callback function which can access an object that contains item variable(as can be seen) which is coming from the child component FlatList . 在这里, FlatList接收一个回调函数,该函数可以访问一个包含item变量的对象(可以看到),该变量来自子组件FlatList It somehow is able to give the object(containing item ) to the callback and still render the item using renderItem prop that is passed to it. 它能够以某种方式将对象(包含item )提供给回调,并仍然使用传递给它的renderItem prop渲染该项目。

I am trying to achieve something similar here: my sandbox 我正在尝试在这里实现类似的目标: 我的沙箱

But I am facing this error which says that React child cannot be a function. 但是我面对这个错误,它说React child不能是一个函数。 The point is completely valid I agree, but I am unable to think of something else as to how to achieve it. 我同意这一观点是完全正确的,但是我无法想到如何实现这一点。 Maybe I am missing some simple concept here. 也许我在这里缺少一些简单的概念。

Any help will be appreciated. 任何帮助将不胜感激。 Thanks in advance! 提前致谢!

As per your sandbox, you need to pass arguments when its being called in order to get any return value. 根据您的沙箱,您需要在调用沙箱时传递参数,以获取任何返回值。 In a class function, you don't need to pass values if you are using class level variables, but in your case you are using arguments to execute the function that is why you need to pass arguments to it. 在类函数中,如果您使用类级变量,则不需要传递值,但是在这种情况下,您是在使用参数执行函数,因此需要向其传递参数。 That is why, you are not able get the value as when your component is rendering summary or details , its finding the reference of the function rather the actual return value. 这就是为什么您无法获得该值,因为当您的组件呈现summarydetails ,它无法找到函数的引用,而不是实际的返回值。

I have made changes to your sandbox to pass dummy values, you can replace it as per your requirements. 我已对您的沙箱进行了更改以传递虚拟值,您可以根据需要替换它。

You should update your code with return statement. 您应该使用return语句更新代码。

<FlatList
    data={[{key: 'a'}, {key: 'b'}]}
    renderItem={({item}) => {
        return <Text>{item.key}</Text>;
    }}
/>

Just simply use ( and ) instead of { } . 只需使用()代替{ } This will return your component. 这将返回您的组件。

<FlatList
  data={[{key: 'a'}, {key: 'b'}]}
  renderItem={({item}) => (
       <Text>{item.key}</Text>
     )   
  }
/>

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

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