父子组件传值练习
效果图
image.png
import React, {Component} from "react";
import PropTypes from "prop-types"
// 子组件
class TabBarItem extends Component {
render() {
const {tab_bars, curr_index} = this.props
return (
<ul>
{
tab_bars.map((item, index) => {
return (
<li
key={index}
onClick={e => this.props.fItemClick(index)}
className={curr_index === index ? "active" : null}
>
{item}</li>
)
})
}
</ul>
)
}
}
// props验证
TabBarItem.propTypes = {
tab_bars: PropTypes.array,
curr_index: PropTypes.number,
fItemClick: PropTypes.func
}
// 父组件
export default class TabBar extends Component {
constructor(props) {
super(props);
this.tab_bars = ["热销", "新上", "推荐"]
this.state = {
curr_index: 0,
curr_title: "热销"
}
}
fItemClick = (index) => {
this.setState({
curr_index: index,
curr_title: this.tab_bars[index]
})
}
render() {
return (
<div>
{
<TabBarItem
tab_bars={this.tab_bars}
curr_index={this.state.curr_index}
fItemClick={index => this.fItemClick(index)}
/>
}
<p>{this.state.curr_title}</p>
</div>
)
}
}
END
网友评论