在嵌套组件中反应组件道具
React component props inside nested component
我很难理解如何构建一个相当简单的组件,该组件具有需要在嵌套组件内部访问的各种道具。我什至不知道这是否是正确解释我的情况的方式,不管我觉得这应该很简单。
我会解释的。我有一个组件如下:
<Widget
layout="small"
header="This is the header"
icon={<UploadIcon/>}
title="This is the title"
caption="This is the caption to a widget it should have a character count"
to="/tosomwhere"
href="http://www.website.com"
link="Link Title"
/>
和组件代码。
const Widget = (props) => {
return (
<WidgetWrapper layout={props.layout}>
hello world
{props.title}
</WidgetWrapper>
);
}
Widget.propTypes = {
layout: PropTypes.oneOf(['small', 'large', 'dual']),
header: PropTypes.string,
icon: PropTypes.element,
title: PropTypes.string,
caption: PropTypes.string,
to: PropTypes.string,
href: PropTypes.string,
link: PropTypes.string,
};
Widget.defaultProps = {
layout: 'small'
};
export default Widget;
如您所见,我在组件内部包含了一个组件。它的目的是纯粹的视觉(小部件的大小、颜色、ext),但它需要包装来自
的所有道具
我可以访问 props.layout
,因为它在组件外部,但我无法访问属于 .
的内部 props.title
这是怎么做到的?我是否需要向下传递道具以便我可以通过这种方式访问它们?我试图添加一个 props={props}
但没有成功...
我认为您不应该在标签中包含这样的道具。我用来编写我的 React 的方式只是像你使用 props.layout
一样在标签内传递道具,然后在你的 WidgetWrapper
.
的代码中使用这些道具
您可以只使用扩展运算符,而不是在标签中写下每一个 prop:
<WidgetWrapper {...props}/>
我不确定我是否完全理解你的问题。你想从 WidgetWrapper 访问 Widget 组件中的一些 props 吗?在这种情况下,我认为你应该传递你需要的东西。或者你有很多道具想传递给包装器吗?
const RenderApp = props => {
return (
<div>
hello {props.title}
</div>
);
}
class App extends React.Component {
render(){
return (
<RenderApp title="world"/>
);
}
}
这对我有用并打印 "hello world"...也许我没抓住要点...
我很难理解如何构建一个相当简单的组件,该组件具有需要在嵌套组件内部访问的各种道具。我什至不知道这是否是正确解释我的情况的方式,不管我觉得这应该很简单。
我会解释的。我有一个组件如下:
<Widget
layout="small"
header="This is the header"
icon={<UploadIcon/>}
title="This is the title"
caption="This is the caption to a widget it should have a character count"
to="/tosomwhere"
href="http://www.website.com"
link="Link Title"
/>
和组件代码。
const Widget = (props) => {
return (
<WidgetWrapper layout={props.layout}>
hello world
{props.title}
</WidgetWrapper>
);
}
Widget.propTypes = {
layout: PropTypes.oneOf(['small', 'large', 'dual']),
header: PropTypes.string,
icon: PropTypes.element,
title: PropTypes.string,
caption: PropTypes.string,
to: PropTypes.string,
href: PropTypes.string,
link: PropTypes.string,
};
Widget.defaultProps = {
layout: 'small'
};
export default Widget;
如您所见,我在组件内部包含了一个组件。它的目的是纯粹的视觉(小部件的大小、颜色、ext),但它需要包装来自
的所有道具我可以访问 props.layout
,因为它在组件外部,但我无法访问属于 .
props.title
这是怎么做到的?我是否需要向下传递道具以便我可以通过这种方式访问它们?我试图添加一个 props={props}
但没有成功...
我认为您不应该在标签中包含这样的道具。我用来编写我的 React 的方式只是像你使用 props.layout
一样在标签内传递道具,然后在你的 WidgetWrapper
.
您可以只使用扩展运算符,而不是在标签中写下每一个 prop:
<WidgetWrapper {...props}/>
我不确定我是否完全理解你的问题。你想从 WidgetWrapper 访问 Widget 组件中的一些 props 吗?在这种情况下,我认为你应该传递你需要的东西。或者你有很多道具想传递给包装器吗?
const RenderApp = props => {
return (
<div>
hello {props.title}
</div>
);
}
class App extends React.Component {
render(){
return (
<RenderApp title="world"/>
);
}
}
这对我有用并打印 "hello world"...也许我没抓住要点...