[英]How to let a parent component manage the state of child components in React?
[英]React: How to dynamically append child components of differing types into a parent component?
我試圖根據傳遞給<ParentComponent/>
的props值附加各種子組件<ChildComponen1/>, <ChildComponen3/>, <ChildComponen3/>
來動態設置組件<ParentComponent/>
的內容。 父組件是一個列表,子組件是具有不同內容(css,html)的列表項
下面,我詳細介紹了一種我認為適合這種情況的方法,但是,如果您有另一種(更有效的)方法來實現使用各種不同的子組件動態填充父組件的指定目標,則將不勝感激。 謝謝
class ParentComponent extends React.Component{
render(){
return(
<ComponentSwitch type="ChildComponen1"/>
<ComponentSwitch type="ChildComponen2"/>
)
}
}
class ComponentSwitch extends React.Component{
render(){
return(
//How would I most effectively create a switch here?
)
}
}
...child components omitted for brevity
實現此功能的最有效方式是什么? 謝謝
只是寫一些Javascript ...
例如,這里有很多可能性:
class ComponentSwitch extends React.Component {
renderA() {
return (
<div>
... lot of child components here
</div>
);
}
render() {
if (this.props.a) {
return this.renderA();
}
return <B />;
}
}
或使用switch
語句並返回組件進行渲染。 不管你做什么
class ComponentSwitch extends React.Component {
render() {
switch (this.props.component) {
case 'a':
return <A />;
case 'b':
return <B />;
default:
return <C />;
}
}
}
做任何JS允許您做的事情:)
我將回答我所理解的問題,我不確定您的真正問題是什么,但是這確實可以解決。
首先,將您的type
參數設置為您希望其表示的真實Class
。
import ChildComponent1 from './ChildComponent1.jsx';
import ChildComponent2 from './ChildComponent2.jsx';
class ParentComponent extends React.Component{
render(){
return(
<ComponentSwitch type={ChildComponen1} name='John'/>
<ComponentSwitch type={ChildComponen2} name='Doe'/>
)
}
}
然后從props
提取type
,並將其余的props
傳遞給子Component
。
class ComponentSwitch extends React.Component{
render(){
const {
type: Component,
...props,
} = this.props;
// props will now have 'name' and other props ready for the child component
return <Component {...props} />;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.