子传父 父传子组件间通信
点开哪一个展开哪一个
<
button onClick = {
() => { changValue("佳佳") }
} > 点我变身 < /button>
class App extends Component {
state = {
name: '鸡胸肉',
hobby: '佳宝贝'
}
changValue = (newName) => {
this.setState({ name: newName })
}
render() {
let { hobby, } = this.state;
return ( <
div >
<
p > { this.state.name } < /p> <
FriendList hobby = { hobby }
changValue = { this.changValue }
/ > < /
div >
);
};
};
export default class friendList extends Component {
state = {
isOpen: "" //哪一项是展开的
}
//传递给子组件,点击那个子组件,子组件就将自身的name传参过来
changeOpen = (name) => {
this.setState({ isOpen: name })
}
render() {
console.log(this.props)
let { isOpen } = this.state
/*
循环数组 根据外部来获取数据
key 开发环境中 ,不建议使用数据的索引
*/
return ( <
div className = "friend-list" > {
Object.keys(data).map((item, index) => {
/*分组传*/
return (
<
Dl key = { index } /*箭头函数里的index*/
name = { item } /*属性名*/
value = { data[item] } /*属性值*/
isOpen = { isOpen }
changeOpen = { this.changeOpen }
/ >
)
})
} < /
div >
)
}
}
export default class Dl extends Component {
// state = {
// isOpen: false
// }
render() {
// console.log(this.props);
let { title, list } = this.props.value;
//name : 记录自身数据的属性名
//isOpen: 哪一项需要展开
//(name==isOpen ? "expanded" : "") 判断是否需要展开
let { name, isOpen, changeOpen } = this.props
return ( <
div className = { "friend-group" + (name == isOpen ? "expanded" : "") } >
<
dt onClick = {
() => {
changeOpen(name)
}
} > { title } < /dt> {
list.map((item, index) => {
return <dd key = { index } > { item.name } < /dd>
})
} <
/
div >
)
}
}