React에서 중첩된 모양에 대한 기본 소품을 제공하려면 어떻게 해야 합니까?
리액트에서는 특정 모양의 아이템의 중첩 배열에 기본 소품을 제공하는 방법이 있습니까?
아래 예에서 첫 번째 시도를 볼 수 있지만 예상대로 되지 않습니다.
static propTypes = {
heading: PT.string,
items: PT.arrayOf(PT.shape({
href: PT.string,
label: PT.string,
})).isRequired,
};
static defaultProps = {
heading: 'this works',
items: [{
href: '/',
label: ' - this does not - ',
}],
};
이 예에서는 다음 사항을 상정하고 있습니다.
// Given these props
const passedInProps = {
items: [{ href: 'foo' }, { href: 'bar' }]
};
// Would resolve to:
const props = {
heading: 'this works',
items: [
{ href: 'foo', label: ' - this does not - ' },
{ href: 'bar', label: ' - this does not - ' },
]
};
아뇨, 기본 소품들은 얄팍하게 합쳐졌을 뿐이에요
그러나 한 가지 방법은 각 항목에 대해 하위 구성 요소를 갖는 것입니다.이렇게 하면 각 Child 컴포넌트는 1개의 오브젝트를item그러면 기본 소품이 예상대로 병합됩니다.
예를 들어 다음과 같습니다.
var Parent = React.createClass({
propTypes: {
heading: React.PropTypes.string,
items: React.PropTypes.arrayOf(React.PropTypes.shape({
href: React.PropTypes.string,
label: React.PropTypes.string,
})).isRequired
},
getDefaultProps: function() {
return {
heading: 'this works',
items: [{
href: '/',
label: ' - this does not - ',
}],
};
},
render: function() {
return (
<div>
{this.props.item.map(function(item) {
return <Child {...item} />
})}
</div>
);
}
});
var Child = React.createClass({
propTypes: {
href: React.PropTypes.string,
label: React.PropTypes.string
},
getDefaultProps: function() {
return {
href: '/',
label: ' - this does not - '
};
},
render: function() {
return (
<div />
<p>href: {this.props.href}</p>
<p>label: {this.props.label}
</div>
);
}
});
전화하는 대신 getter를 사용할 수 있습니다.this.props비싼 방법이 되려면 아이템이 많아야 합니다.수정도 가능합니다.items아래처럼 세팅했는데 리액트는 소품에서 상태를 도출하지 말 것을 제안합니다.
class Foo extends React.Component {
static propTypes = {
heading: PropTypes.string,
items: PropTypes.arrayOf(PropTypes.shape({
href: PropTypes.string,
label: PropTypes.string,
})).isRequired
}
static defaultLabel = ' - this does not - '
static defaultHref = '/'
get items() {
return this.props.items.map((item) => ({
href: item.href || this.defaultHref,
label: item.label || this.defaultLabel,
}));
}
render() {
return (
<div>
{this.items.map(({href, label}) => <a href={href}>{label}</a>)}
</div>
);
}
}
언급URL : https://stackoverflow.com/questions/38123498/how-do-you-provide-default-props-for-nested-shape-in-react
'source' 카테고리의 다른 글
| 일부 요소에 대해 nganimate 사용 안 함 (0) | 2023.02.12 |
|---|---|
| "Newtonsoft에서 항목을 추가하거나 제거할 수 없습니다.Json.Linq.JProperty"를 참조해 주세요. (0) | 2023.02.12 |
| JSON 세트를 시리얼화하는 방법 (0) | 2023.02.12 |
| @PathVariable을 사용한 Spring MVC 주석 컨트롤러 인터페이스 (0) | 2023.02.12 |
| WooCommerce 쿠폰은 데이터베이스에 어떻게 저장됩니까? (0) | 2023.02.12 |