在无状态子组件中传递/访问道具 [英] Passing/Accessing props in stateless child component

查看:167
本文介绍了在无状态子组件中传递/访问道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以将所有的反应组件道具传递给它的子组件,如下所示:

I know you can pass all a react components props to it's child component like this:

const ParentComponent = () => (
   <div>
     <h1>Parent Component</h1>
     <ChildComponent {...this.props} />
   </div>
)

但如果子组件是无状态的,那么如何检索这些道具呢?我知道如果它是一个类组件,你可以只以 this.prop.whatever 的形式访问它们,但是你将什么作为参数传递给无状态组件?

But how do you then retrieve those props if the child component is stateless? I know if it is a class component you can just access them as this.prop.whatever, but what do you pass as the argument into the stateless component?

const ChildComponent = ({ *what goes here?* }) => (
   <div>
      <h1>Child Component</h1>
   </div>
)


推荐答案

写作时

const ChildComponent = ({ someProp }) => (
   <div>
      <h1>Child Component {someProp}</h1>
   </div>
)

从您传递给 childComponent 的所有道具中,您只需要进行解构即可获得只有 someProp 。如果要在ChildComponents中使用的道具数量在可用的道具总数中是可数的(很少),则解构是一个很好的选择,因为它提供了更好的可读性。

From all the props that you are passing to the childComponent you are just destructuring to get only someProp. If the number of props that you want to use in ChildComponents are countable(few) amongst the total number of props that are available, destructuring is a good option as it provides better readability.

假设你想要访问子组件中的所有道具,那么你不需要在参数周围使用 {} 然后你可以使用它像 props.someProp

Suppose you want to access all the props in the child component then you need not use {} around the argument and then you can use it like props.someProp

const ChildComponent = (props) => (
   <div>
      <h1>Child Component {props.someProp}</h1>
   </div>
)

这篇关于在无状态子组件中传递/访问道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆