React组件中的子prop [英] children prop in React component
问题描述
我正在学习当下的反应。这是与代码的链接 - http://redux.js.org/docs/ basics / ExampleTodoList.html
i am learning react at the moment. this is the link with the code - http://redux.js.org/docs/basics/ExampleTodoList.html
我在理解这部分代码中发生的事情时遇到了一些困难
I am having a bit of difficulty understanding what's going on in this part of the code
const Link = ({ active, children, onClick }) => {
if (active) {
return <span>{children}</span>
}
return (
<a
href="#"
onClick={e => {
e.preventDefault()
onClick()
}}
>
{children}
</a>
)
}
Link.propTypes = {
active: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
onClick: PropTypes.func.isRequired
}
我最难理解这个片段
return (
<a
href="#"
onClick={e => {
e.preventDefault()
onClick()
}}
>
{children}
</a>
)
}
{children}在这里意味着什么?
它做什么?
What does {children} mean here? What does it do?
这是做什么用的?
children: PropTypes.node.isRequired,
上述行中的节点是什么意思?
what is meant by node in the above line?
推荐答案
当您使用自定义组件时,例如
When you use a Custom component, like
<MyComponent>Hello World</MyComponent>
无论你在标签之间写什么(在上面的例子中,Hello World)都作为<传递给组件code>孩子道具。
Whatever you write between the tags (in above case Hello World) is passed to the component as a children
prop.
因此在编写你的组件时
const Link = ({ active, children, onClick }) => {
您正在对道具进行解构并仅获得有效$ c $传递给组件的道具中的c>,
children
和 onClick
You are destructuring the props and getting only active
, children
and onClick
from the props passed to the component
例如,您可以调用 Link
组件,例如
Consider for example, you call the Link
component like
<Link active="true" onClick={someFunc} style={{color: 'orange'}}>Hello</Link>
然后在所有道具中,即活跃,onClick,风格,儿童
,您只能访问组件中的 active,onClick,children
。
Then amongst all the props i.e active, onClick, style, children
, you will only be accessing active, onClick,children
in the component.
第二个问题:
这是做什么的?
and what does this do?
children:PropTypes。 node.isRequired,
children: PropTypes.node.isRequired,
所以这里 PropTypes
是一种执行typeCheck的方法在传递给组件的道具上。它是从 react-proptypes
包中导入的。
So here PropTypes
is a way of performing a typeCheck on the props that are passed to the component. It is being imported from the react-proptypes
package.
所以
children: PropTypes.node.isRequired
使prop children
成为必需。因此,如果您渲染您的组件
makes the prop children
to be required. So if your render your component like
<Link />
它不会通过类型检查,因此你需要做
It will not pass the type check and hence you need to do
<Link>Text</Link>
这篇关于React组件中的子prop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!