如何使用 React.js 将状态 属性 传递给构造函数中的子组件?
How to pass state property to child component in constructor with React.js?
如何在构造函数中将父组件的状态属性作为子组件的 props 传递?我有这样的东西:
class FatherComponent extends Component {
constructor(props) {
super(props);
this.state = {
status: true
components: [
{ component: (
<ChildComponent
statusAsProps={this.state.status} />
)
}
]
};
}
render(){
return(
<div>{this.state.components[0].component}</div>
)
}
但显示 this.state 的错误未定义。
是一种将状态 "this" 绑定为子组件的道具的方法吗?
在状态上存储组件不是一个好主意。您可以在 render
中定义它
class FatherComponent extends Component {
constructor(props) {
super(props);
this.state = {
status: true
};
}
render(){
return(
<div>
{ <ChildComponent statusAsProps={this.state.status} }
</div>
)
}
方法
您甚至在定义和赋值之前就在其内部使用了 this.state
。这就是 undefined
的原因。避免复杂性,通过从父级状态传入所需的道具来简单地渲染子组件。
class FatherComponent extends Component {
constructor(props) {
super(props);
this.state = {
status: true
};
}
render() {
return (
<div>
<ChildComponent statusAsProps={this.state.status} />
</div>
)
}
}
如何在构造函数中将父组件的状态属性作为子组件的 props 传递?我有这样的东西:
class FatherComponent extends Component {
constructor(props) {
super(props);
this.state = {
status: true
components: [
{ component: (
<ChildComponent
statusAsProps={this.state.status} />
)
}
]
};
}
render(){
return(
<div>{this.state.components[0].component}</div>
)
}
但显示 this.state 的错误未定义。 是一种将状态 "this" 绑定为子组件的道具的方法吗?
在状态上存储组件不是一个好主意。您可以在 render
class FatherComponent extends Component {
constructor(props) {
super(props);
this.state = {
status: true
};
}
render(){
return(
<div>
{ <ChildComponent statusAsProps={this.state.status} }
</div>
)
}
方法
您甚至在定义和赋值之前就在其内部使用了 this.state
。这就是 undefined
的原因。避免复杂性,通过从父级状态传入所需的道具来简单地渲染子组件。
class FatherComponent extends Component {
constructor(props) {
super(props);
this.state = {
status: true
};
}
render() {
return (
<div>
<ChildComponent statusAsProps={this.state.status} />
</div>
)
}
}