- 使用children动态传递子组件
Counter.jsx
import React, { Component } from "react";
class Counter extends Component {
state = {
value: this.props.value
};
// 按钮点击事件,value+1
handleIncrement = () => {
this.setState({ value: this.state.value + 1 });
};
render() {
console.log("props", this.props);
return (
<div>
{this.props.children}
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button
onClick={this.handleIncrement}
className="btn btn-secondary btn-sm"
>
Increment
</button>
</div>
);
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.value === 0 ? "warning" : "primary";
return classes;
}
formatCount() {
const { value } = this.state;
return value === 0 ? "zero" : value;
}
}
export default Counter;
Counters.jsx
import React, { Component } from "react";
import Counter from "./counter";
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 4 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
render() {
return (
<div>
{this.state.counters.map(counter => (
<Counter key={counter.id} value={counter.value}>
<h4>Counter #{counter.id}</h4>
</Counter>
))}
</div>
);
}
}
export default Counters;
- 直接传入另一个属性:
Counters.jsx
<div>
{this.state.counters.map(counter => (
<Counter key={counter.id} value={counter.value} id={counter.id} />
))}
</div>
Counter.jsx
<div>
<h4>{this.props.id}</h4>
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
- 当你想传递一个复杂的对象,比如说一个对话框,这时候使用Children属性比较好,其他情况还是推荐使用第二种。